<?php

namespace app\api\controller;

use think\Db;
use think\Log;
use aliyun\OssDemo;
use OSS\OssClient;

class User extends Base
{
    public function _initialize()
    {
        extract(input());
        if (!isset($mini)) {
            $sta = $this->checkAll($user_id, $time, $value, $reqKey);
            if (!$sta) {
                return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
            }
        }
        if (isset($user_id) && $user_id == '12331') {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        parent::_initialize();
    }


    public function getBanner()
    {
//        $a = $this->jpushUser(1, 1,  "测试", json([]));
//        dump($a);die;
        extract(input());
//        $pid = Db::name('area')->where(['district_id'=>$area])->value('pid');
//        $sheng_id = Db::name('area')->where(['district_id'=>$pid])->value('pid');
//        $exists = Db::name('admin')->where(['area'=>$sheng_id])->find();
//        $sheng = [];
//        if(!empty($exists)){
//            $num = 1;
//            $sheng = Db::name('banner')->where(['b_area_id'=>$sheng_id,'b_type'=>2,'b_model'=>1])->limit (1)->column('b_address');
//        }else{
//            $num = 2;
//        }
//        $qu = Db::name('banner')->where(['b_area_id'=>$area,'b_type'=>3,'b_model'=>1])->limit(3)->column('b_address');
//        $zong = Db::name('banner')->where(['b_type'=>1,'b_model'=>1])->limit ($num)->column('b_address');
//        return json(['status'=>200,'msg'=>array_merge ($zong,$sheng,$qu)]);
        $zong = Db::name('banner')->where(['b_type' => 1, 'b_model' => 1])->limit(5)->column('b_address');
        return json(['status' => 200, 'msg' => $zong]);
    }


    public function getWinInfo()
    {
        extract(input());
        $map = [];
        if (isset($user_id) && $user_id) {
            $map['w_user_id'] = $user_id;
        }
        $data = Db::name('win_info w')
            ->join('u_user u', 'u.user_id = w.w_user_id', 'left')
            ->where($map)
            ->whereTime('w_add_time', '-3 day')
            ->field(['w_id', 'w_info', 'user_id', 'user_username', 'user_image', 'w_type', 'w_code'])
            ->order('w_add_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function getTreasureList()
    {
        extract(input());
        $data = Db::name('d_treasure d')
            ->join('product p', 'd.d_product_id = p.p_id', 'left')
            ->join('shop s', 'd.d_shop_id = s.shop_id', 'left')
            ->where("(d_status=2 AND shop_qu_id={$qu}) OR (d_status=2 AND d_country=2)")
            ->field('d.*,p_banner,p_name')
            ->page($page, 10)
            ->order('d_sort desc')
            ->select();

        return json(['status' => 200, 'msg' => $data]);
    }


    public function myJoinList()
    {
        extract(input());
        $data = Db::name('d_join j')
            ->join('d_treasure t', 'j.j_treasure_id = t.d_id', 'left')
            ->join('product p', 'p.p_id = t.d_product_id', 'left')
            ->where(['j_user_id' => $user_id])
            ->field('t.*,j_win_code,j_is_win,p.p_banner,p.p_name')
            ->page($page, 10)
            ->order('j_join_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function treasureDetail()
    {
        extract(input());
        $data = Db::name('d_treasure t')
            ->join('product p', 't.d_product_id = p.p_id', 'left')
            ->field('t.*,p.p_banner,p.p_content')
            ->where(['d_id' => $d_id])
            ->find();
        $data['p_content'] = str_replace(",,,,,","",$data['p_content']);
        return json(['status' => 200, 'msg' => $data]);
    }


    public function joinTreasure()
    {
        extract(input());
        $info = Db::name('d_treasure d')
            ->join('product p', 'd.d_product_id = p.p_id', 'left')
            ->where('d_id', $d_id)
            ->find();
        if ($info['d_join'] >= $info['d_join_num']) {
            return json(['status' => 100, 'msg' => '人数已满，等待开奖']);
        }
        if($info['d_status'] !=2 && $info['d_status'] != 4){
            return json(['status' => 100, 'msg' => '活动已失效']);
        }
        // 判断用户有没有地址
        $defaultAddressCount = Db::name('address')
            ->where(['add_user_id' => $user_id, 'add_default' => 2])
            ->count();
        if (0 == $defaultAddressCount) {
            return json(['status' => 100, 'msg' => '积分抽奖有机会中实物礼品哦，请先完善收货地址信息']);
        }

        Db::startTrans();
        try {
            //锁表
            $exists = Db::name('d_join')->lock(true)->where(['j_treasure_id' => $d_id, 'j_user_id' => $user_id])->find();
            $exists2 = Db::name('d_join')->where(['j_treasure_id' => $d_id, 'j_user_id' => $user_id])->find();
            if ($exists || $exists2) {
                return json(['status' => 100, 'msg' => '请勿重复参加']);
            }
            $my = Db::name('u_user')->where('user_id', $user_id)->find();
            $sum = Db::name('jifen')->where(['jifen_user_id' => $user_id])->sum('jifen_number');
            if ($sum < $cost) {
                return json(['status' => 100, 'msg' => '积分不足']);
            }
            $code = $this->getTreasureCode($d_id);
            $param = [
                'j_treasure_id' => $d_id,
                'j_user_id'     => $user_id,
                'j_win_code'    => $code,
                'j_join_time'   => date('Y-m-d H:i:s')
            ];
            $j_id = Db::name('d_join')->insertGetId($param);
            Db::name('win_info')->insert(['w_info' => "参与了" . $info['p_name'] . "的积分夺宝", 'w_user_id' => $user_id, 'w_add_time' => date("Y-m-d H:i:s"), 'w_code' => $code]);

            $back = $this->treasureCost($user_id, input('cost'), $j_id);
            if ($back['status'] == 100) {
                return json($back);
            }

            Db::name('jifen_consume')->insert(['consume_content' => '参与积分夺宝消费' . $cost . '积分', 'consume_user_id' => $user_id, 'consume_add_time' => date('Y-m-d H:i:s')]);

            Db::name('d_treasure')->where('d_id', $d_id)->setInc('d_join', 1);

            $winuid = 0;
            $joinHaveWin = Db::name('d_join')
                ->where('j_treasure_id', $d_id)
                ->where('j_is_win', 2)
                ->count();
            if ($info['d_join'] + 1 == $info['d_join_num'] && $info['d_type'] == 1 && $joinHaveWin <= 0 && in_array($info['d_status'],[2,4])) {

                $time = date('Y-m-d H:i:s');
                $join = Db::name('d_join')->where('j_treasure_id', $d_id)->group('j_user_id')->select();
                $j_jifen = Db::name('d_jifen')->where(['co_j_id' => ['in', array_column($join, 'j_id')], 'co_status' => 1])->select();
                $code = array_column($join, 'j_win_code');
                $user = array_column($join, 'j_user_id');
                $win = $code[array_rand($code)];
                $list = array_search($win, $code);
                $name = Db::name('d_treasure t')
                    ->join('product p', 't.d_product_id = p.p_id', 'left')
                    ->join('shop s', 's.shop_id = p.p_shop_id', 'left')
                    ->where(['d_id' => $info['d_id']])
                    ->find();
                $rate = Db::name('jifen_conf')->where('conf_id', 2)->value('conf_rate');
                $mon = array_sum(array_column($j_jifen, 'co_jifen')) * $rate;
                foreach ($user as $k => $v) {
                    if ($v != $user[$list]) {
                        Db::name('d_join')->where(['j_treasure_id' => $info['d_id'], 'j_user_id' => $v])->update(['j_is_win' => 3, 'j_open_time' => $time]);
                        Db::name('notice')->insert(['n_to' => 1, 'n_title' => '积分夺宝', 'n_content' => '您参加的' . $name['p_name'] . '积分夺宝的已开奖，抱歉未中奖！', 'n_images' => $name['p_banner'], 'n_type' => 5, 'n_user_id' => $v, 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s'), 'n_where_id' => '']);
                        try {
                            $this->jpushUser(1, $v, "您参加的" . $name['p_name'] . "积分夺宝的已开奖，抱歉未中奖！", json([]));
                        } catch (\Exception $e) {}
                    } else {
                        $winuid = $v;
                        Db::name('d_join')->where(['j_treasure_id' => $info['d_id'], 'j_user_id' => $v])->update(['j_is_win' => 2, 'j_open_time' => $time]);

                        $addr = Db::name('address a')
                            ->join('area s', 's.district_id = a.add_province', 'left')
                            ->join('area c', 'c.district_id = a.add_city', 'left')
                            ->join('area q', 'q.district_id = a.add_area', 'left')
                            ->where('add_user_id', $v)
                            ->field('a.*,s.district sheng,c.district shi,q.district qu')
                            ->find();
                        $j_order_num = $this->getOrderNumber();
                        $order_for = [
                            'o_type'       => 2,
                            'o_user_id'    => $v,
                            'o_order_num'  => $j_order_num,
                            'o_money'      => $name['d_price'],
                            'o_status'     => $name['d_send_type'] == 2 ? 2 : 10,
                            'o_pay_status' => 2,
                            'o_shop_id'    => $name['p_shop_id'],
                            'o_shop_name'  => $name['shop_name'],
                            'o_esp'        => 2,
                            'o_esp_money'  => $mon,
                            'o_add_time'   => date('Y-m-d H:i:s')
                        ];
                        if (!empty($addr)) {
                            $order_for['o_name'] = $addr['add_name'];
                            $order_for['o_phone'] = $addr['add_phone'];
                            $order_for['o_address'] = $addr['sheng'] . $addr['shi'] . $addr['qu'] . $addr['add_detail'];
                        }
                        if ($name['p_deliver_cate'] == 1 || $name['p_deliver_cate'] == 3) {
                            $order_for['o_cate'] = 1;
                        } else {
                            $order_for['o_qrcode'] = http_type() . "/api/shop/scanQrcodeOrder?num=" . $j_order_num;
                            $order_for['o_cate'] = $name['p_deliver_cate'];
                        }
                        $j_get_id = Db::name('order')->insertGetId($order_for);
                        $info_for = [
                            'oi_order_id'    => $j_get_id,
                            'oi_goods_id'    => $name['d_product_id'],
                            'oi_goods_name'  => $name['p_name'],
                            'oi_goods_image' => $name['p_banner'],
                            'oi_goods_price' => $name['d_price'],
                            'oi_goods_jifen' => 0,
                            'oi_goods_model' => $name['d_model'],
                            'oi_num'         => 1,
                            'oi_total_price' => $name['d_price'],
                            'oi_total_jifen' => 0
                        ];
                        Db::name('order_info')->insert($info_for);

                        Db::name('win_info')->insert(['w_info' => '参与积分夺宝活动,获得' . $name['p_name'], 'w_user_id' => $v, 'w_add_time' => $time, 'w_code' => $win]);
                        Db::name('notice')->insert(['n_to' => 1, 'n_title' => '积分夺宝', 'n_content' => '您参加的' . $name['p_name'] . '积分夺宝的已开奖，恭喜中奖！', 'n_images' => $name['p_banner'], 'n_type' => 5, 'n_user_id' => $v, 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s'), 'n_where_id' => $name['p_id']]);
                    }
                }
                $ba = [
                    'o_type'       => 10,
                    'o_money'      => $mon,
                    'o_status'     => 5,
                    'o_pay_status' => 2,
                    'o_shop_id'    => $name['p_shop_id'],
                    'o_add_time'   => date('Y-m-d H:i:s')
                ];
                Db::name('order')->insertGetId($ba);
                foreach ($j_jifen as $key => $vo) {
                    $this->profit($vo['co_jifen'], $info['d_shop_id'], $vo['co_from']);
                    if ($vo['co_from'] == 1) {
                        Db::name('admin')->where('id', 1)->setInc('integral', $vo['co_jifen']);
                    } else {
                        Db::name('admin')->where(['area' => $vo['co_from']])->setInc('integral', $vo['co_jifen']);
                    }
                    Db::name('d_jifen')->where('co_id', $vo['co_id'])->setField('co_status', 2);
                }

                Db::name('shop')->where('shop_id', $name['p_shop_id'])->setInc('shop_balance_yet', $mon);

                Db::name('notice')->insert(['n_to' => 2, 'n_title' => '积分夺宝', 'n_content' => '您发布的积分夺宝的已开奖！', 'n_images' => $name['p_banner'], 'n_type' => 5, 'n_user_id' => $info['d_shop_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);

                $this->jpushShop(1, $info['d_shop_id'], '您发布的积分夺宝的已开奖！', json([]));

                Db::name('d_treasure')->where(['d_id' => $info['d_id']])->update(['d_status' => 5, 'd_win_time' => $time, 'd_win_code' => $win, 'd_win_user_id' => $user[$list]]);
            }
            Db::commit();
            if($winuid > 0){
                try {
                    $this->jpushUser(1, $winuid, '您参加的' . $name['p_name'] . '积分夺宝的已开奖，恭喜中奖！', json([]));
                } catch (\Exception $e) {}
            }
            return json(['status' => 200, 'msg' => $code]);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '参加失败']);
        }
    }


    public function winList()
    {
        extract(input());
        $data = Db::name('d_join j')
            ->join('d_treasure t', 'j.j_treasure_id = t.d_id', 'left')
            ->where(['j_is_win' => ['neq', 1], 'j_user_id' => $user_id])
            ->field(['j.*', 'd_win_code', "DATE_FORMAT(d_win_time, '%m/%d')" => 'd_win_time'])
            ->order('d_win_time desc')
            ->page($page, 10)
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function tjGoods()
    {
        extract(input());
        $today = Db::name('product p')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where(['p_type' => ['in', '2,3'], 'p_status' => 4, 'p_today_th' => 2])
            ->order('p_sort desc')
            ->limit(6)
            ->select();
        $city = Db::name('product p')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where(['p_type' => ['in', '2,3'], 'p_status' => 4, 'p_city_th' => 2, 'shop_qu_id' => $qu])
            ->order('p_sort desc')
            ->limit(6)
            ->select();
        if (empty($city)) {
            $city = Db::name('product p')
                ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
                ->where(['p_type' => ['in', '2,3'], 'p_status' => 4, 'p_city_th_zong' => 2])
                ->order('p_sort desc')
                ->limit(6)
                ->select();
        }
        $man = Db::name('product p')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where(['p_type' => ['in', '2,3'], 'p_status' => 4, 'p_man_tj' => 2, 'shop_qu_id' => $qu])
            ->order('p_sort desc')
            ->limit(4)
            ->select();
        if (empty($man)) {
            $man = Db::name('product p')
                ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
                ->where(['p_type' => ['in', '2,3'], 'p_status' => 4, 'p_man_tj_zong' => 2])
                ->order('p_sort desc')
                ->limit(4)
                ->select();
        }
        $roll = Db::name('ad')
            ->where(['ad_type' => 2, 'ad_qu_id' => $qu, 'ad_port' => 1])
            ->select();
        if (empty($roll)) {
            $roll = Db::name('ad')
                ->where(['ad_type' => 1, 'ad_port' => 1])
                ->select();
        }
        $shop = Db::name('shop s')
            ->where(['shop_status' => 1, 'shop_attestation' => 2, 'shop_qu_id' => $qu])
            ->where('shop_id', 'IN', function ($query) {
                $query->table('up_product')->alias('p')->where('p.p_shop_id=s.shop_id AND p.p_status=4')->field('p_shop_id');
            })
            ->field('shop_id,shop_name,shop_img,shop_introduce,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((' . $lat . '* PI() / 180 - shop_lat * PI() / 180) / 2),2) + COS(' . $lat . ' * PI() / 180) * COS(shop_lat * PI() / 180) * POW(SIN((' . $lon . ' * PI() / 180 - shop_lon * PI() / 180) / 2),2))),2) AS distance,shop_browse,(SELECT COUNT(1) FROM up_record_rule r WHERE r.rule_shop_id = s.shop_id) AS is_record,shop_address')
            ->limit(8)
            ->order('distance asc')
            ->select();
        if (!empty($shop)) {
            foreach ($shop as $key => $vo) {
                $product_ids = DB::name('product')->where('p_shop_id', $vo['shop_id'])->column('p_id');
                if (!empty($product_ids)) {
                    $star = DB::name('appraise')->where(['app_p_id' => ['in', $product_ids]])->avg('app_type');
                    if (!empty($star)) {
                        $star = ceil($star);
                        // 店铺星级，所有商品评价平均值
                        $shop[$key]['p_star'] = $star;
                    } else {
                        // 没有商品给5星
                        $shop[$key]['p_star'] = 5;
                    }
                } else {
                    // 没有商品给5星
                    $shop[$key]['p_star'] = 5;
                }
            }
        }
        $data = [
            'today' => $today,
            'city'  => $city,
            'man'   => $man,
            'roll'  => $roll,
            'shop'  => $shop
        ];
        return json(['status' => 200, 'msg' => $data]);
    }


    public function getAdvertise()
    {
        extract(input());
        $ad = Db::name('ad')
            ->where(['ad_type' => 2, 'ad_qu_id' => $qu, 'ad_port' => $port, 'ad_postion' => $postion])
            ->field("ad_id,ad_img,ad_link,ad_type,ad_qu_id,ad_user_id,ad_add_time,ad_left_title,CONCAT(ad_right_title,'人推荐') as ad_right_title,ad_port,ad_cate,ad_postion,ad_edit_time")
            ->order('ad_sort desc')
            ->select();
        if (empty($ad)) {
            $ad = Db::name('ad')
                ->where(['ad_type' => 1, 'ad_port' => $port, 'ad_postion' => $postion])
                ->field("ad_id,ad_img,ad_link,ad_type,ad_qu_id,ad_user_id,ad_add_time,ad_left_title,CONCAT(ad_right_title,'人推荐') as ad_right_title,ad_port,ad_cate,ad_postion,ad_edit_time")
                ->order('ad_sort desc')
                ->select();
        }

        return json(['status' => 200, 'msg' => $ad]);
    }


    public function setIncAd()
    {
        extract(input());
        $res = Db::name('ad')->where('ad_id', $ad_id)->setInc('ad_right_title');
        if ($res) {
            return json(['status' => 200, 'msg' => '自增成功']);
        } else {
            return json(['status' => 100, 'msg' => '自增失败']);
        }
    }


    public function hotCity()
    {
        extract(input());
        $data = Db::name('hot_city h')
            ->join('area a', 'a.district_id = hot_qu', 'left')
            ->column('district');
        return json(['status' => 200, 'msg' => $data]);
    }


    public function moreData()
    {
        extract(input());
        $where = [
            'p_type'   => ['in', '2,3'],
            'p_status' => 4,
//            'shop_qu_id'=>$qu
        ];
        if ($cate) {
            $where['p_cate'] = $cate;
        }
        switch ($type) {
            case 1:
                $where['p_today_th'] = 2;
                break;
            case 2:
                $where['p_city_th'] = 2;
                break;
            case 3:
                $where['p_man_tj'] = 2;
                break;
        }
        switch ($sort) {
            case 1:
                $xu = 'p_jifen_price desc';
                break;
            case 2:
                $xu = 'p_jifen_price asc';
                break;
            case 3:
                $xu = 'p_sell_yet desc';
                break;
            default:
                $xu = 'p_attestation_time desc';
        }
        $data = Db::name('product')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where($where)
            ->page($page, 10)
            ->order($xu)
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function hotGoods()
    {
        extract(input());
        $where = [
            'p_type'   => ['in', '2,3'],
            'p_status' => 4,
            'p_hot'    => 2
        ];
        if ($cate) {
            $where['p_cate'] = $cate;
        }
        if (isset($qu) && $qu) {
            $where['shop_qu_id'] = $qu;
        }
        $data = Db::name('product')
            ->join('shop', 'p_shop_id=shop_id', 'left')
            ->where($where)
            ->page($page, 10)
            ->order("p_attestation_time desc")
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function getCatList()
    {
        extract(input());
        $data = Db::name('product_cate')
            ->where(['cate_level' => 2])
            ->order('cate_sort ASC')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }

    /**
     * ->where('shop_id', 'IN', function ($query) {
     * $query->table('up_product')->alias('p')->where('p.p_shop_id=s.shop_id AND p.p_status=4')->field('p_shop_id');
     * })
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function nearbyShop()
    {
        extract(input());
        $sids = Db::name('product')->where('p_status',4)->group('p_shop_id')->column('p_shop_id');
        $shop = Db::name('shop s')
            ->where(['shop_status' => 1, 'shop_attestation' => 2, 'shop_qu_id' => $qu])
            ->where('shop_id','in',$sids)
            ->field('shop_id,shop_name,shop_img,shop_introduce,shop_browse,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((' . $lat . '* PI() / 180 - shop_lat * PI() / 180) / 2),2) + COS(' . $lat . ' * PI() / 180) * COS(shop_lat * PI() / 180) * POW(SIN((' . $lon . ' * PI() / 180 - shop_lon * PI() / 180) / 2),2))),2) AS distance,(SELECT COUNT(1) FROM up_record_rule r WHERE r.rule_shop_id = s.shop_id) AS is_record')
            ->page($page, 10)
            ->order('distance asc')
            ->select();
        if (!empty($shop)) {
            foreach ($shop as $key => $vo) {
                $product_ids = DB::name('product')->where('p_shop_id', $vo['shop_id'])->column('p_id');
                if (!empty($product_ids)) {
                    $star = DB::name('appraise')->where(['app_p_id' => ['in', $product_ids]])->avg('app_type');
                    if (!empty($star)) {
                        $star = ceil($star);
                        // 店铺星级，所有商品评价平均值
                        $shop[$key]['p_star'] = $star;
                    } else {
                        // 没有商品给5星
                        $shop[$key]['p_star'] = 5;
                    }
                } else {
                    // 没有商品给5星
                    $shop[$key]['p_star'] = 5;
                }
            }
        }
        return json(['status' => 200, 'msg' => $shop]);
    }


    public function search()
    {
        extract(input());
        if ($type == 1) {
            $data = Db::name('product')
                ->where(['p_status' => 4, 'p_name' => ['like', '%' . $key . '%']])
                ->page($page, 10)
                ->order('p_attestation_time desc')
                ->select();
        } else {
            $data = Db::name('u_user')
                ->where("user_status = 1  AND user_id <> {$user_id} AND (user_username LIKE '%{$key}%' OR user_phone = '{$key}')")
                ->page($page, 10)
                ->order('user_time desc')
                ->select();
            if (!empty($data)) {
                foreach ($data as $key => $vo) {
                    $is = Db::name('user_fellow')->where(['fellow_user_id' => $user_id, 'fellow_star_user_id' => $vo['user_id']])->find();
                    !empty($is) ? $data[$key]['is_focus'] = true : $data[$key]['is_focus'] = false;
                }
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function getFundList()
    {
        extract(input());
        $data = Db::name('fund')
            ->where("(fund_status=2 AND fund_qu_id={$qu}) OR (fund_status=2 AND fund_country=2)")
            ->page($page, 10)
            ->order('fund_check_time desc')
            ->select();
        foreach ($data as $key => $vo) {
            if ($vo['fund_join'] > 0) {
                $img = Db::name('fund_join j')
                    ->join('u_user u', 'j.j_user_id = u.user_id', 'left')
                    ->where(['j_fund_id' => $vo['fund_id']])
                    ->column('user_image');
                $data[$key]['head'] = $img;
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function myFund()
    {
        extract(input());
        if ($type == 1) {
            $data = Db::name('fund_join j')
                ->join('fund f', 'f.fund_id = j.j_fund_id', 'left')
                ->where(['j_user_id' => $user_id])
                ->page($page, 10)
                ->order('j_pay_time desc')
                ->group('fund_id')
                ->select();
            if (!empty($data)) {
                foreach ($data as $key => $vo) {
                    $data[$key]['my'] = Db::name('fund_join')->where(['j_fund_id' => $vo['fund_id'], 'j_user_id' => $user_id])->sum('j_pay');
                }
            }
        } else {
            $data = Db::name('fund')
                ->where(['fund_user_id' => $user_id, 'fund_status' => ['neq', 6]])
                ->page($page, 10)
                ->order('fund_check_time desc')
                ->select();
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function fundDetail()
    {
        extract(input());
        $data = Db::name('fund f')
            ->join('u_user u', 'f.fund_user_id = u.user_id', 'left')
            ->where(['fund_id' => $fund_id])
            ->field('f.*,u.user_username,u.user_image')
            ->find();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function newFund()
    {
        extract(input());
        $time = date('Y-m-d H:i:s');
        $param = [
            'fund_title'        => $title,
            'fund_plan'         => $plan,
            'fund_introduction' => $introduction,
            'fund_imgs'         => $imgs,
            'fund_end_time'     => $end_time,
            'fund_user_id'      => $user_id,
            'fund_qu_id'        => $qu,
            'fund_add_time'     => $time,
            'fund_edit_time'    => $time
        ];
        $res = Db::name('fund')->insert($param);
        if ($res) {
            try {
                $this->jpushUser(1, $user_id, '众筹发布成功', json([]));
            } catch (\Exception $e) {}
            return json(['status' => 200, 'msg' => '发布成功']);
        } else {
            return json(['status' => 100, 'msg' => '发布失败']);
        }
    }


    public function joinFund()
    {
        extract(input());
        $fund = Db::name('fund')->where('fund_id', $fund_id)->find();
        if ($fund['fund_status'] == 2 && $fund['fund_money'] >= $fund['fund_plan']) {
            Db::name('fund')->where('fund_id', $fund_id)->setField('fund_status', 5);
            Db::name('fund_join')->where('j_fund_id', $fund_id)->setField('j_status', 2);
            return json(['status' => 100, 'msg' => '该众筹已结束']);
        }
        if ($money > (string)($fund['fund_plan'] - $fund['fund_money'])) {
            return json(['status' => 100, 'msg' => '最多还可众筹' . (string)($fund['fund_plan'] - $fund['fund_money']) . '元']);
        }
        $order = $this->getOrderNumber();
        $param = [
            'o_type'       => 9,
            'o_order_num'  => $order,
            'o_money'      => $money,
            'o_status'     => 5,
            'o_pay_type'   => $type,
            'o_pay_status' => 1,
            'o_user_id'    => $user_id,
            'o_fund_id'    => $fund_id,
            'o_add_time'   => date('Y-m-d H:i:s')
        ];
        Db::name('order')->insert($param);
        if ($type == 1) {
            $ali = new Ali();
            $res = $ali->getParam($order, $money, 'joinFund', '参与众筹');
        } else {
            $wx = new Weixin();
            $obj = [
                'attach'       => "joinFund",
                'body'         => "参与众筹",
                'total_fee'    => $money * 100,
                'out_trade_no' => $order,
                'product_id'   => "",
                'trade_type'   => "APP"
            ];
            $res = $wx->WeChatPayReady($obj);
        }
        return json(['status' => 200, 'msg' => $res]);
    }


    public function jifenConversion()
    {
        extract(input());
        $where = [
            'p_type'   => ['in', '2,3'],
            'p_status' => 4,
        ];
        if ($cate) {
            $where['p_cate'] = $cate;
        }
        switch ($sort) {
            case 1:
                $xu = 'p_jifen_price desc';
                break;
            case 2:
                $xu = 'p_jifen_price asc';
                break;
            case 3:
                $xu = 'p_sell_yet desc';
                break;
        }
        $data = Db::name('product')
            ->where($where)
            ->order($xu)
            ->page($page, 10)
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function getGameBanner()
    {
        extract(input());
        $banner = Db::name('banner')
            ->where(['b_area_id' => $qu, 'b_model' => 2])
            ->column('b_address');
        if (empty($banner)) {
            $banner = Db::name('banner')
                ->where(['b_type' => 1, 'b_model' => 2])
                ->column('b_address');
        }
        $user = Db::name('u_user')
            ->where('user_id', $user_id)
            ->field(['user_lottery_number', 'user_lottery_time'])
            ->find();
        if ($user['user_lottery_time'] == '' || $user['user_lottery_time'] != date('Y-m-d')) {
            Db::name('u_user')->where('user_id', $user_id)->setField('user_lottery_number', 10);
            $num = 10;
        } else {
            $num = $user['user_lottery_number'];
        }
        $data = [
            'banner' => $banner,
            'number' => $num
        ];
        return json(['status' => 200, 'msg' => $data]);
    }


    public function jifenGame()
    {
        extract(input());
        $him = Db::name('u_user')->where('user_id', $user_id)->find();
        $number = $him['user_lottery_number'];
        if ($number <= 0) {
            return json(['status' => 100, 'msg' => '抽奖次数不足']);
        }
        $sum = Db::name('jifen')->where(['jifen_user_id' => $user_id])->sum('jifen_number');
        if ($sum < 10) {
            return json(['status' => 100, 'msg' => '积分不足']);
        }

        // 判断用户有没有地址
        $defaultAddressCount = Db::name('address')
            ->where(['add_user_id' => $user_id, 'add_default' => 2])
            ->count();
        if (0 == $defaultAddressCount) {
            return json(['status' => 100, 'msg' => '积分抽奖有机会中实物礼品哦，请先完善收货地址信息']);
        }
        // 实物每人只能中一次
        $user_prize = DB::name('order')
            ->where(['o_type' => 2, 'o_pay_status' => 2, 'o_esp' => 3, 'o_user_id' => $user_id])
            ->column('o_id');
        if (!empty($user_prize)) {
            $prize_goods_id = DB::name('order_info')
                ->where(['oi_order_id' => ['in', $user_prize]])
                ->column('oi_goods_id');

        }
        if (!empty($prize_goods_id)) {
            $where['prize_goods_id'] = ['not in', $prize_goods_id];
        }
        $where['prize_a_id'] = 1;
        $prize_arr = Db::name('prize')
            ->where($where)
            ->where('prize_num', '>', 0)
            ->field(['prize_id' => 'id', 'prize_name' => 'prize', 'prize_probability' => 'v', 'prize_type', 'prize_jifen', 'prize_a_id', 'prize_goods_id'])
            ->select();
        $place = 1134;
        if (empty($prize_arr)) {
            return json(['status' => 100, 'msg' => '抽奖暂未开放']);
        }
        $arr = [];
        foreach ($prize_arr as $key => $val) {
            $arr[$key] = $val['v'];
        }
        $rid = $this->get_rand($arr);
        $res = [
            'name' => $prize_arr[$rid]['prize'],
            'id'   => $rid
        ];
        Db::startTrans();
        try {
            $back = $this->consume($user_id, 10, '000');
            if ($back['status'] == 100) {
                return json($back);
            }

            if ($prize_arr[$rid]['prize_type'] == 1) {
                // 积分不超过100
                if ($prize_arr[$rid]['prize_jifen'] >= 101) {
                    return json(['status' => 100, 'msg' => '抽奖积分错误']);
                }
                DB::name('admin')->where('area', $place)->setDec('integral', $prize_arr[$rid]['prize_jifen']);
                $this->jifenFlow($prize_arr[$rid]['prize_jifen'], $place, $user_id, 'jifenGame');

                Db::name('jifen_consume')->insert(['consume_content' => '积分抽奖获得' . $prize_arr[$rid]['prize_jifen'] . '积分', 'consume_user_id' => $user_id, 'consume_add_time' => date('Y-m-d H:i:s')]);

            } else {
                $name = Db::name('product p')
                    ->join('shop s', 's.shop_id = p.p_shop_id', 'left')
                    ->where('p_id', $prize_arr[$rid]['prize_goods_id'])
                    ->find();
                $addr = Db::name('address a')
                    ->join('area s', 's.district_id = a.add_province', 'left')
                    ->join('area c', 'c.district_id = a.add_city', 'left')
                    ->join('area q', 'q.district_id = a.add_area', 'left')
                    ->where('add_user_id', $user_id)
                    ->field('a.*,s.district sheng,c.district shi,q.district qu')
                    ->find();
                $j_order_num = $this->getOrderNumber();
                $order_for = [
                    'o_type'       => 2,
                    'o_user_id'    => $user_id,
                    'o_order_num'  => $j_order_num,
                    'o_money'      => $name['p_now_price'],
                    // 'o_status'=>$name['p_deliver_cate'] == 1 ? 2 : 10,
                    'o_status'     => in_array($name['p_deliver_cate'], [1, 3]) ? 2 : 10,
                    'o_pay_status' => 2,
                    'o_shop_id'    => $name['p_shop_id'],
                    'o_shop_name'  => $name['shop_name'],
                    'o_esp'        => 3,
                    'o_add_time'   => date('Y-m-d H:i:s')
                ];
                if (!empty($addr)) {
                    $order_for['o_name'] = $addr['add_name'];
                    $order_for['o_phone'] = $addr['add_phone'];
                    $order_for['o_address'] = $addr['sheng'] . $addr['shi'] . $addr['qu'] . $addr['add_detail'];
                }
                if ($name['p_deliver_cate'] == 1 || $name['p_deliver_cate'] == 3) {
                    $order_for['o_cate'] = 1;
                } else {
                    $order_for['o_qrcode'] = http_type() . "/api/shop/scanQrcodeOrder?num=" . $j_order_num;
                    $order_for['o_cate'] = $name['p_deliver_cate'];
                }
                $j_get_id = Db::name('order')->insertGetId($order_for);
                $info_for = [
                    'oi_order_id'    => $j_get_id,
                    'oi_goods_id'    => $name['p_id'],
                    'oi_goods_name'  => $name['p_name'],
                    'oi_goods_image' => $name['p_banner'],
                    'oi_goods_price' => $name['p_now_price'],
                    'oi_goods_jifen' => 0,
                    'oi_goods_model' => '',
                    'oi_num'         => 1,
                    'oi_total_price' => $name['p_now_price'],
                    'oi_total_jifen' => 0
                ];
                Db::name('order_info')->insert($info_for);
            }
            Db::name('win_info')->insert(['w_info' => '恭喜抽中' . $res['name'], 'w_user_id' => $user_id, 'w_type' => 2, 'w_add_time' => date('Y-m-d H:i:s')]);
            Db::name('jifen_consume')->insert(['consume_content' => '抽奖消费10积分', 'consume_user_id' => $user_id, 'consume_add_time' => date('Y-m-d H:i:s')]);

            Db::name('u_user')->where('user_id', $user_id)->update(['user_lottery_number' => $number - 1, 'user_lottery_time' => date('Y-m-d'), 'user_edit_time' => date('Y-m-d H:i:s')]);


            Db::name('notice')->insert(['n_to' => 1, 'n_title' => '积分抽奖', 'n_content' => '您参与积分抽奖，恭喜抽中' . $res['name'], 'n_images' => '', 'n_type' => 5, 'n_user_id' => $user_id, 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);

            try {
                // $this->jpushUser(1,$user_id,'您参与积分抽奖，恭喜抽中'.$res['name'],json([]));
            } catch (\Exception $e) {
            }

            $join = Db::name('c_join')->where('c_user_id', $user_id)->find();
            if (empty($join)) {
                Db::name('c_join')->insert(['c_user_id' => $user_id, 'c_user_img' => $him['user_image'], 'c_add_time' => date('Y-m-d H:i:s')]);
            }
            Db::name('prize')->where('prize_id', $prize_arr[$rid]['id'])->setDec('prize_num');
            Db::commit();
            return json(['status' => 200, 'msg' => $res]);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            file_put_contents(APP_PATH . "api/controller/test.txt", date("Y-m-d H:i:s") . "  " . $e . "\r\n", FILE_APPEND);
            return json(['status' => 100, 'msg' => '抽奖失败']);
        }
    }


    public function goodsDetail()
    {
        extract(input());
        if (empty($qu)) {
            $qu = 1134;
        }
        $goods = Db::name('product p')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where(['p_id' => $p_id])
            ->field('p.*,shop_id,shop_name,shop_img,shop_address,shop_contact')
            ->find();
        if($goods['p_content']){
            $goods['p_content'] = "<div style='padding-left:10px;padding-right:10px;'>" . $goods['p_content'] . "</div>";
        }
        Db::name('shop')->where(['shop_id' => $goods['shop_id']])->setInc('shop_browse');
        // 先查询本地的
        $arr = Db::name('product p')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where(['p.p_cate' => $goods['p_cate'], 'p.p_status' => 4, 'p.p_id' => ['neq', $p_id], 's.shop_qu_id' => $qu])
            ->field('p.p_id,p.p_type,p.p_banner,p.p_name,p.p_old_price,p.p_now_price,p.p_jifen_price,p.p_deliver_cate')
            ->limit(6)
            ->order('p.p_attestation_time desc')
            ->select();
        $arrLen = count($arr);
        if (6 > $arrLen) {
            // 查询包邮和邮费的
            $arr2 = Db::name('product')
                ->where(['p_cate' => $goods['p_cate'], 'p_status' => 4, 'p_id' => ['neq', $p_id], 'p_deliver_cate' => ['in', [1, 3]]])
                ->field('p_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_deliver_cate')
                ->limit(6 - $arrLen)
                ->order('p_attestation_time desc')
                ->select();
            $arr = array_merge($arr, $arr2);
        }
        $count = Db::name('appraise')
            ->where(['app_p_id' => $p_id])
            ->count();
        $first = Db::name('appraise a')
            ->join('u_user u', 'a.app_user_id = u.user_id', 'left')
            ->where(['app_p_id' => $p_id])
            ->field('a.*,u.user_username,u.user_image')
            ->select();
        $collect = Db::name('collect')
            ->where(['col_type' => 1, 'col_sp_id' => $p_id])
            ->find();
        if (!empty($collect)) {
            $goods['collect'] = true;
        } else {
            $goods['collect'] = false;
        }
        $model = [];
        if ($goods['p_model'] == 2) {
            $model = Db::name('product_model')
                ->where(['m_product_id' => $p_id])
                ->select();
            $num = 0;
            foreach ($model as $key => $vo) {
                $num += $vo['m_num'];
            }
            $goods['p_stock_num'] = $num;
        }
        return json(['status' => 200, 'msg' => ['goods' => $goods, 'arr' => $arr, 'count' => $count, 'first' => $first, 'model' => $model]]);
    }


    public function goodsAppraise()
    {
        extract(input());
        $where = [
            'app_p_id' => $p_id
        ];
        switch ($type) {
            case 1:
                $where['app_imgs'] = ['neq', ''];
                break;
            case 2:
                $where['app_type'] = ['in', '4,5'];
                break;
            case 3:
                $where['app_type'] = 3;
                break;
            case 4:
                $where['app_type'] = ['in', '1,2'];
                break;
        }
        $data = Db::name('appraise a')
            ->join('u_user u', 'a.app_user_id = u.user_id', 'left')
            ->where($where)
            ->field('a.*,u.user_username,u.user_image')
            ->page($page, 10)
            ->order('app_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function getShopDetail()
    {
        extract(input());
        $shop = Db::name('shop')
            ->where(['shop_id' => $shop_id])
            ->field(['shop_id', 'shop_banner', 'shop_img', 'shop_name', 'shop_business_hours', 'ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((' . $lat . '* PI() / 180 - shop_lat * PI() / 180) / 2),2) + COS(' . $lat . ' * PI() / 180) * COS(shop_lat * PI() / 180) * POW(SIN((' . $lon . ' * PI() / 180 - shop_lon * PI() / 180) / 2),2))),2)' => 'distance', 'shop_introduce', 'shop_address', 'shop_contact', 'shop_qu_id', 'shop_lon', 'shop_lat', 'shop_link'])
            ->find();
        if (!$shop['shop_banner']) {
            $shop['shop_banner'] = ',';
        }
        if (!empty($shop)) {
            $product_ids = DB::name('product')->where('p_shop_id', $shop['shop_id'])->column('p_id');
            if (!empty($product_ids)) {
                $star = DB::name('appraise')->where(['app_p_id' => ['in', $product_ids]])->avg('app_type');
                if (!empty($star)) {
                    $star = ceil($star);
                    // 店铺星级，所有商品评价平均值
                    $shop['p_star'] = $star;
                } else {
                    // 没有商品给5星
                    $shop['p_star'] = 5;
                }
            } else {
                // 没有商品给5星
                $shop['p_star'] = 5;
            }
        }
        $ad = Db::name('ad')
            ->where(['ad_qu_id' => $shop['shop_qu_id'], 'ad_type' => 2, 'ad_port' => 1])
            ->select();
        if (empty($ad)) {
            $ad = Db::name('ad')
                ->where(['ad_type' => 1, 'ad_port' => 1])
                ->select();
        }
        $have = Db::name('collect')
            ->where(['col_type' => 2, 'col_user_id' => $user_id, 'col_sp_id' => $shop_id])
            ->find();
        Db::name('shop')->where(['shop_id' => $shop_id])->setInc('shop_browse');
        if (!empty($have)) {
            $collect = true;
        } else {
            $collect = false;
        }
        return json(['status' => 200, 'msg' => ['shop' => $shop, 'ad' => $ad, 'collect' => $collect]]);
    }


    public function getShopGoods()
    {
        extract(input());
        if (empty($page_size)) {
            $page_size = 10;
        }
        $where = [
            'p_shop_id' => $shop_id,
            'p_status'  => 4
        ];
        if ($type == 1) {
            $where['p_type'] = ['in', '2,3'];
        } else {
            $where['p_type'] = 1;
        }
        $data = Db::name('product')
            ->where($where)
            ->page($page, $page_size)
            ->order('p_attestation_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function collect()
    {
        extract(input());
        $param = [
            'col_type'     => $type,
            'col_user_id'  => $user_id,
            'col_sp_id'    => $col_id,
            'col_add_time' => date('Y-m-d H:i:s')
        ];
        $res = Db::name('collect')->insert($param);
        if ($res) {
            Db::name('u_user')->where('user_id', $user_id)->setInc("user_collect");
            return json(['status' => 200, 'msg' => '收藏成功']);
        } else {
            return json(['status' => 100, 'msg' => '收藏失败']);
        }
    }


    public function cancelCollect()
    {
        extract(input());
        $res = Db::name('collect')->where(['col_type' => $type, 'col_user_id' => $user_id, 'col_sp_id' => $col_id])->delete();
        if ($res) {
            Db::name('u_user')->where('user_id', $user_id)->setDec("user_collect");
            return json(['status' => 200, 'msg' => '取消收藏成功']);
        } else {
            return json(['status' => 100, 'msg' => '取消收藏失败']);
        }
    }


    public function shopCar()
    {
        extract(input());
        $shop = Db::name('shop_car c')
            ->join('shop s', 's.shop_id = c.car_shop_id', 'left')
            ->where(['car_user_id' => $user_id])
            ->field('car_shop_id,car_shop_name,shop_img')
            ->order('car_add_time desc')
            ->group('car_shop_id')
            ->page($page, 10)
            ->select();

        if (!empty($shop)) {
            foreach ($shop as $key => $vo) {
                $goods = Db::name('shop_car')
                    ->where(['car_user_id' => $user_id, 'car_shop_id' => $vo['car_shop_id']])
                    ->order('car_add_time desc')
                    ->select();
                foreach ($goods as $k => $v) {
                    $goods[$k]['p_status'] = 3;
                    $p = Db::name('product')
                        ->where(['p_id' => $v['car_product_id']])
                        ->find();
                    if ($p['p_status'] == 5 || $p['p_status'] == 6) {
                        $goods[$k]['p_status'] = 1;
                    }
                    if ($v['car_m_id'] == '' || !$v['car_m_id'] || $v['car_m_id'] <= 0) {
                        if ($p['p_stock_num'] == 0) {
                            $goods[$k]['p_status'] = 2;
                        } elseif ($p['p_stock_num'] > 0 && $p['p_stock_num'] < $v['car_buy_num']) {
                            Db::name('shop_car')->where(['car_id' => $v['car_id']])->setField('car_buy_num', $p['p_stock_num']);
                            $goods[$k]['car_buy_num'] = $p['p_stock_num'];
                        }
                        $goods[$k]['p_stock_num'] = $p['p_stock_num'];
                    } else {
                        $mod = Db::name('product_model')
                            ->where(['m_id' => $v['car_m_id']])
                            ->find();
                        $goods[$k]['p_stock_num'] = $mod['m_num'];
                        if ($mod['m_num'] == 0) {
                            $goods[$k]['p_status'] = 2;
                        } elseif ($mod['m_num'] > 0 && $mod['m_num'] < $v['car_buy_num']) {
                            Db::name('shop_car')->where(['car_id' => $v['car_id']])->setField('car_buy_num', $mod['m_num']);
                            $goods[$k]['car_buy_num'] = $mod['m_num'];
                        }
                    }
                }
                $shop[$key]['goods'] = $goods;
            }
        }
        return json(['status' => 200, 'msg' => $shop]);
    }


    public function delShopCar()
    {
        extract(input());
        $res = Db::name('shop_car')
            ->where(['car_id' => ['in', $ids]])
            ->delete();
        if ($res) {
            return json(['status' => 200, 'msg' => '删除成功']);
        } else {
            return json(['status' => 100, 'msg' => '删除失败']);
        }
    }


    public function addShopCar()
    {
        extract(input());
        $goods = Db::name('product')->where(['p_id' => $p_id])->find();
        $car = Db::name('shop_car')->where(['car_user_id' => $user_id, 'car_product_id' => $p_id])->find();
        $sum = Db::name('shop_car')->where(['car_user_id' => $user_id, 'car_product_id' => $p_id])->sum('car_buy_num');
        $inte = Db::name('shop')->where('shop_id', $goods['p_shop_id'])->find();

        if ($goods['p_type'] == 1) {
            $all_order = Db::name('order')->where(['o_type' => 2, 'o_shop_id' => $goods['p_shop_id'], 'o_status' => ['in', '2,3'], 'o_esp' => 1])->select();
            $must = 0;
            if (!empty($all_order)) {
                foreach ($all_order as $vv) {
                    $pro = Db::name('order_info')->where('oi_order_id', $vv['o_id'])->select();
                    foreach ($pro as $z) {
                        $give = Db::name('product')->where(['p_id' => $z['oi_goods_id']])->value('p_give');
                        $must = $must + ($give * $z['oi_num']);
                    }
                }
            }
            //这一块是积分押金不足的判断
//            if ($goods['p_give'] > 0 && ($goods['p_give'] > ($inte['shop_integral'] - $must) || $inte['shop_pledge_money'] <= 0)) {
//                Db::name('product')->where(['p_id' => $p_id])->setField('p_status', 5);
//                Db::name('notice')->insert(['n_to' => 2, 'n_title' => '系统消息', 'n_content' => '积分押金不足，请尽快充值押金', 'n_images' => '', 'n_type' => 1, 'n_user_id' => $goods['p_shop_id'], 'n_read' => ',0,', 'n_delete' => ',0,', 'n_time' => date('Y-m-d H:i:s')]);
//
//                $this->jpushShop(1, $goods['p_shop_id'], '积分押金不足，请尽快充值押金', json([]));
//
//                return json(['status' => 100, 'msg' => '积分押金不足']);
//            }
        }

        if ($goods['p_status'] == 5 || $goods['p_status'] == 6) {
            return json(['status' => 100, 'msg' => '商品已下架']);
        }
        if ($buy_num < 1) {
            return json(['status' => 100, 'msg' => '购买数量有误']);
        }
        if ($goods['p_buy_limit'] > 0 && $buy_num > $goods['p_buy_limit']) {
            return json(['status' => 100, 'msg' => '超过限购数量']);
        }
        if ($goods['p_buy_limit'] > 0 && $buy_num + $sum > $goods['p_buy_limit']) {
            return json(['status' => 100, 'msg' => '超过限购数量']);
        }
        //----------------专门判断限购一份的 start -----------------
        if($goods['p_buy_limit'] > 0){
            $haveBuy = Db::name('order_info')->alias('oi')
                ->join('order o','oi.oi_order_id = o.o_id')
                ->where('o_user_id', $user_id)
                ->where('oi_goods_id', $p_id)
                ->where('o_pay_status', 2)
                ->count();
            if($haveBuy+$buy_num > $goods['p_buy_limit']) return json(['status' => 100, 'msg' => "限购{$goods['p_buy_limit']}份，您已经购买过此商品了"]);
        }

        //----------------专门判断限购一份的  end ------------------
        if($goods['p_now_price'] != $price || $goods['p_jifen_price'] != $integral) return json(['status' => 100, 'msg' => '价格或积分有误']);
        if($goods['p_postage'] != $postage) return json(['status' => 100, 'msg' => '邮费有误']);
        $param = [
            'car_type'         => $goods['p_type'],
            'car_user_id'      => $user_id,
            'car_product_id'   => $p_id,
            'car_product_name' => $goods['p_name'],
            'car_product_img'  => $goods['p_banner'],
            'car_m_id'         => $m_id,
            'car_m_name'       => $m_name,
            'car_m_price'      => $price,
            'car_m_integral'   => $integral,
            'car_shop_id'      => $shop_id,
            'car_shop_name'    => $shop_name,
            'car_buy_num'      => $buy_num,
            'car_cate'         => $cate,
            'car_postage'      => $postage,
            'car_add_time'     => date('Y-m-d H:i:s'),
            'car_edit_time'    => date('Y-m-d H:i:s')
        ];
        Db::startTrans();
        try {
            if ($m_id != "") {
                $car1 = Db::name('shop_car')->where(['car_user_id' => $user_id, 'car_product_id' => $p_id, 'car_m_id' => $m_id])->find();
                if (!empty($car1)) {
                    Db::name('shop_car')->where(['car_user_id' => $user_id, 'car_product_id' => $p_id, 'car_m_id' => $m_id])->setInc('car_buy_num', $buy_num);
                } else {
                    Db::name('shop_car')->insert($param);
                }
            } else {
                if (!empty($car)) {
                    Db::name('shop_car')->where(['car_user_id' => $user_id, 'car_product_id' => $p_id])->setInc('car_buy_num', $buy_num);
                } else {
                    Db::name('shop_car')->insert($param);
                }
            }
            Db::commit();
            return json(['status' => 200, 'msg' => '加入购物车成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '加入购物车失败']);
        }

    }


    public function changNum()
    {
        extract(input());
        if ($num < 1) {
            return json(['status' => 100, 'msg' => '不能再少啦']);
        }
        $car = Db::name('shop_car')->where('car_id', $car_id)->find();
        $info = Db::name('product')->where('p_id', $p_id)->find();
        if ($info['p_buy_limit'] > 0 && $info['p_buy_limit'] < $num) {
            return json(['status' => 100, 'msg' => '超过限购数量']);
        }
        //----------------专门判断限购一份的 start -----------------
        if ($info['p_buy_limit'] > 0) {
            $haveBuy = Db::name('order_info')->alias('oi')
                ->join('order o','oi.oi_order_id = o.o_id')
                ->where('o_user_id', $user_id)
                ->where('oi_goods_id', $p_id)
                ->where('o_pay_status', 2)
                ->count();
            if($haveBuy+$num > $info['p_buy_limit']) return json(['status' => 100, 'msg' => "限购{$info['p_buy_limit']}份，您已经购买过此商品了"]);
        }
        //----------------专门判断限购一份的  end ------------------
        if ($car['car_m_id']) {
            $model = Db::name('product_model')->where('m_id', $car['car_m_id'])->find();
            if ($model['m_num'] < $num) {
                return json(['status' => 100, 'msg' => '已达最大库存', 'num' => $model['m_num']]);
            }
        } else {
            if ($info['p_stock_num'] < $num) {
                return json(['status' => 100, 'msg' => '已达最大库存', 'num' => $info['p_stock_num']]);
            }
        }
        $res = Db::name('shop_car')->where('car_id', $car_id)->update(['car_buy_num' => $num, 'car_edit_time' => date('Y-m-d H:i:s')]);
        if ($res) {
            return json(['status' => 200, 'msg' => '修改成功']);
        } else {
            return json(['status' => 100, 'msg' => '修改失败']);
        }
    }


    public function doMath()
    {
        extract(input());
        $car = explode(',', $car);
        $shop = Db::name('shop_car')->where(['car_id' => ['in', $car]])->column('car_shop_id');
        $shop = array_unique($shop);
        $order = [];
        Db::startTrans();
        try {
            if (!empty($shop)) {
                foreach ($shop as $key => $vo) {
                    $info = Db::name('shop')->where('shop_id', $vo)->find();
                    $j_post = Db::name('shop_car')
                        ->where(['car_shop_id' => $vo, 'car_id' => ['in', $car], 'car_type' => ['in', '2,3'], 'car_cate' => ['in', '1,3']])
                        ->field('*,(car_m_price * car_buy_num) price,(car_m_integral * car_buy_num) integral')
                        ->select();
                    $j_arrive_get = Db::name('shop_car')
                        ->where(['car_shop_id' => $vo, 'car_id' => ['in', $car], 'car_type' => ['in', '2,3'], 'car_cate' => 2])
                        ->field('*,(car_m_price * car_buy_num) price,(car_m_integral * car_buy_num) integral')
                        ->select();
                    $j_arrive_use = Db::name('shop_car')
                        ->where(['car_shop_id' => $vo, 'car_id' => ['in', $car], 'car_type' => ['in', '2,3'], 'car_cate' => 4])
                        ->field('*,(car_m_price * car_buy_num) price,(car_m_integral * car_buy_num) integral')
                        ->select();
                    $c_post = Db::name('shop_car')
                        ->where(['car_shop_id' => $vo, 'car_id' => ['in', $car], 'car_type' => 1, 'car_cate' => ['in', '1,3']])
                        ->field('*,(car_m_price * car_buy_num) price')
                        ->select();
                    $c_arrive_get = Db::name('shop_car')
                        ->where(['car_shop_id' => $vo, 'car_id' => ['in', $car], 'car_type' => 1, 'car_cate' => 2])
                        ->field('*,(car_m_price * car_buy_num) price')
                        ->select();
                    $c_arrive_use = Db::name('shop_car')
                        ->where(['car_shop_id' => $vo, 'car_id' => ['in', $car], 'car_type' => 1, 'car_cate' => 4])
                        ->field('*,(car_m_price * car_buy_num) price')
                        ->select();
                    if (!empty($j_post)) {
                        $j_order = $this->getOrderNumber();
                        $postage = array_column($j_post, 'car_postage');
                        $price = array_column($j_post, 'price');
                        $integral = array_column($j_post, 'integral');
                        $j_param = [
                            'o_type'       => 1,
                            'o_user_id'    => $user_id,
                            'o_order_num'  => $j_order,
                            'o_money'      => array_sum($price) + max($postage),
                            'o_jifen'      => array_sum($integral),
                            'o_status'     => 1,
                            'o_pay_status' => 1,
                            'o_shop_id'    => $vo,
                            'o_shop_name'  => $info['shop_name'],
                            'o_cate'       => max($postage) ? 3 : 1,
                            'o_postage'    => max($postage) ? max($postage) : '',
                            'o_name'       => $name,
                            'o_phone'      => $phone,
                            'o_address'    => $address,
                            'o_add_time'   => date("Y-m-d H:i:s"),
                            'o_lose_time'  => date('Y-m-d H:i:s', strtotime('+1 day'))
                        ];
                        $j_get_id = Db::name('order')->insertGetId($j_param);
                        foreach ($j_post as $v) {
                            $j_info_param[] = [
                                'oi_order_id'    => $j_get_id,
                                'oi_goods_id'    => $v['car_product_id'],
                                'oi_goods_name'  => $v['car_product_name'],
                                'oi_goods_image' => $v['car_product_img'],
                                'oi_goods_price' => $v['car_m_price'],
                                'oi_goods_jifen' => $v['car_m_integral'],
                                'oi_goods_model' => $v['car_m_name'],
                                'oi_num'         => $v['car_buy_num'],
                                'oi_total_price' => $v['car_buy_num'] * $v['car_m_price'],
                                'oi_total_jifen' => $v['car_buy_num'] * $v['car_m_integral']
                            ];
                        }
                        Db::name('order_info')->insertAll($j_info_param);
                        $order[] = $j_order;
                    }
                    if (!empty($c_post)) {
                        $j_order1 = $this->getOrderNumber();
                        $postage1 = array_column($c_post, 'car_postage');
                        $price1 = array_column($c_post, 'price');
                        $j_param1 = [
                            'o_type'       => 2,
                            'o_user_id'    => $user_id,
                            'o_order_num'  => $j_order1,
                            'o_money'      => array_sum($price1) + max($postage1),
                            'o_status'     => 1,
                            'o_pay_status' => 1,
                            'o_shop_id'    => $vo,
                            'o_shop_name'  => $info['shop_name'],
                            'o_cate'       => max($postage1) ? 3 : 1,
                            'o_postage'    => max($postage1) ? max($postage1) : '',
                            'o_name'       => $name,
                            'o_phone'      => $phone,
                            'o_address'    => $address,
                            'o_add_time'   => date("Y-m-d H:i:s"),
                            'o_lose_time'  => date('Y-m-d H:i:s', strtotime('+1 day'))
                        ];
                        $j_get_id1 = Db::name('order')->insertGetId($j_param1);
                        foreach ($c_post as $v) {
                            $j_info_param1[] = [
                                'oi_order_id'    => $j_get_id1,
                                'oi_goods_id'    => $v['car_product_id'],
                                'oi_goods_name'  => $v['car_product_name'],
                                'oi_goods_image' => $v['car_product_img'],
                                'oi_goods_price' => $v['car_m_price'],
                                'oi_goods_model' => $v['car_m_name'],
                                'oi_num'         => $v['car_buy_num'],
                                'oi_total_price' => $v['car_buy_num'] * $v['car_m_price'],
                                'oi_total_jifen' => $v['car_buy_num'] * $v['car_m_integral']
                            ];
                        }
                        Db::name('order_info')->insertAll($j_info_param1);
                        $order[] = $j_order1;
                    }
                    if (!empty($j_arrive_get)) {
                        $j_order2 = $this->getOrderNumber();
                        $price2 = array_column($j_arrive_get, 'price');
                        $integral2 = array_column($j_arrive_get, 'integral');
                        $j_param2 = [
                            'o_type'       => 1,
                            'o_user_id'    => $user_id,
                            'o_order_num'  => $j_order2,
                            'o_money'      => array_sum($price2),
                            'o_jifen'      => array_sum($integral2),
                            'o_status'     => 1,
                            'o_pay_status' => 1,
                            'o_shop_id'    => $vo,
                            'o_shop_name'  => $info['shop_name'],
                            'o_cate'       => 2,
                            'o_qrcode'     => http_type() . "/api/shop/scanQrcodeOrder?num=" . $j_order2,
                            'o_name'       => $name,
                            'o_phone'      => $phone,
                            'o_address'    => $address,
                            'o_add_time'   => date("Y-m-d H:i:s"),
                            'o_lose_time'  => date('Y-m-d H:i:s', strtotime('+1 day'))
                        ];
                        $j_get_id2 = Db::name('order')->insertGetId($j_param2);
                        foreach ($j_arrive_get as $v) {
                            $j_info_param2[] = [
                                'oi_order_id'    => $j_get_id2,
                                'oi_goods_id'    => $v['car_product_id'],
                                'oi_goods_name'  => $v['car_product_name'],
                                'oi_goods_image' => $v['car_product_img'],
                                'oi_goods_price' => $v['car_m_price'],
                                'oi_goods_jifen' => $v['car_m_integral'],
                                'oi_goods_model' => $v['car_m_name'],
                                'oi_num'         => $v['car_buy_num'],
                                'oi_total_price' => $v['car_buy_num'] * $v['car_m_price'],
                                'oi_total_jifen' => $v['car_buy_num'] * $v['car_m_integral']
                            ];
                        }
                        Db::name('order_info')->insertAll($j_info_param2);
                        $order[] = $j_order2;
                    }
                    if (!empty($j_arrive_use)) {
                        $j_order3 = $this->getOrderNumber();
                        $price3 = array_column($j_arrive_use, 'price');
                        $integral3 = array_column($j_arrive_use, 'integral');
                        $j_param3 = [
                            'o_type'       => 1,
                            'o_user_id'    => $user_id,
                            'o_order_num'  => $j_order3,
                            'o_money'      => array_sum($price3),
                            'o_jifen'      => array_sum($integral3),
                            'o_status'     => 1,
                            'o_pay_status' => 1,
                            'o_shop_id'    => $vo,
                            'o_shop_name'  => $info['shop_name'],
                            'o_cate'       => 4,
                            'o_qrcode'     => http_type() . "/api/shop/scanQrcodeOrder?num=" . $j_order3,
                            'o_name'       => $name,
                            'o_phone'      => $phone,
                            'o_address'    => $address,
                            'o_add_time'   => date("Y-m-d H:i:s"),
                            'o_lose_time'  => date('Y-m-d H:i:s', strtotime('+1 day'))
                        ];
                        $j_get_id3 = Db::name('order')->insertGetId($j_param3);
                        foreach ($j_arrive_use as $v) {
                            $j_info_param3[] = [
                                'oi_order_id'    => $j_get_id3,
                                'oi_goods_id'    => $v['car_product_id'],
                                'oi_goods_name'  => $v['car_product_name'],
                                'oi_goods_image' => $v['car_product_img'],
                                'oi_goods_price' => $v['car_m_price'],
                                'oi_goods_jifen' => $v['car_m_integral'],
                                'oi_goods_model' => $v['car_m_name'],
                                'oi_num'         => $v['car_buy_num'],
                                'oi_total_price' => $v['car_buy_num'] * $v['car_m_price'],
                                'oi_total_jifen' => $v['car_buy_num'] * $v['car_m_integral']
                            ];
                        }
                        Db::name('order_info')->insertAll($j_info_param3);
                        $order[] = $j_order3;
                    }
                    if (!empty($c_arrive_get)) {
                        $j_order4 = $this->getOrderNumber();
                        $price4 = array_column($c_arrive_get, 'price');
                        $j_param4 = [
                            'o_type'       => 2,
                            'o_user_id'    => $user_id,
                            'o_order_num'  => $j_order4,
                            'o_money'      => array_sum($price4),
                            'o_status'     => 1,
                            'o_pay_status' => 1,
                            'o_shop_id'    => $vo,
                            'o_shop_name'  => $info['shop_name'],
                            'o_cate'       => 2,
                            'o_qrcode'     => http_type() . "/api/shop/scanQrcodeOrder?num=" . $j_order4,
                            'o_name'       => $name,
                            'o_phone'      => $phone,
                            'o_address'    => $address,
                            'o_add_time'   => date("Y-m-d H:i:s"),
                            'o_lose_time'  => date('Y-m-d H:i:s', strtotime('+1 day'))
                        ];
                        $j_get_id4 = Db::name('order')->insertGetId($j_param4);
                        foreach ($c_arrive_get as $v) {
                            $j_info_param4[] = [
                                'oi_order_id'    => $j_get_id4,
                                'oi_goods_id'    => $v['car_product_id'],
                                'oi_goods_name'  => $v['car_product_name'],
                                'oi_goods_image' => $v['car_product_img'],
                                'oi_goods_price' => $v['car_m_price'],
                                'oi_goods_model' => $v['car_m_name'],
                                'oi_num'         => $v['car_buy_num'],
                                'oi_total_price' => $v['car_buy_num'] * $v['car_m_price'],
                                'oi_total_jifen' => $v['car_buy_num'] * $v['car_m_integral']
                            ];
                        }
                        Db::name('order_info')->insertAll($j_info_param4);
                        $order[] = $j_order4;
                    }
                    if (!empty($c_arrive_use)) {
                        $j_order5 = $this->getOrderNumber();
                        $price5 = array_column($c_arrive_use, 'price');
                        $j_param5 = [
                            'o_type'       => 2,
                            'o_user_id'    => $user_id,
                            'o_order_num'  => $j_order5,
                            'o_money'      => array_sum($price5),
                            'o_status'     => 1,
                            'o_pay_status' => 1,
                            'o_shop_id'    => $vo,
                            'o_shop_name'  => $info['shop_name'],
                            'o_cate'       => 4,
                            'o_qrcode'     => http_type() . "/api/shop/scanQrcodeOrder?num=" . $j_order5,
//                            'o_name'=>$name,
//                            'o_phone'=>$phone,
//                            'o_address'=>$address,
                            'o_add_time'   => date("Y-m-d H:i:s"),
                            'o_lose_time'  => date('Y-m-d H:i:s', strtotime('+1 day'))
                        ];
                        $j_get_id5 = Db::name('order')->insertGetId($j_param5);
                        foreach ($c_arrive_use as $v) {
                            $j_info_param5[] = [
                                'oi_order_id'    => $j_get_id5,
                                'oi_goods_id'    => $v['car_product_id'],
                                'oi_goods_name'  => $v['car_product_name'],
                                'oi_goods_image' => $v['car_product_img'],
                                'oi_goods_price' => $v['car_m_price'],
                                'oi_goods_model' => $v['car_m_name'],
                                'oi_num'         => $v['car_buy_num'],
                                'oi_total_price' => $v['car_buy_num'] * $v['car_m_price'],
                                'oi_total_jifen' => $v['car_buy_num'] * $v['car_m_integral']
                            ];
                        }
                        Db::name('order_info')->insertAll($j_info_param5);
                        $order[] = $j_order5;
                    }
                }
            }
            Db::name('shop_car')->where(['car_id' => ['in', $car]])->delete();
            Db::name('notice')->insert(['n_to' => 1, 'n_title' => '购物订单', 'n_content' => '您的订单，下单成功！', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $user_id, 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);

            try {
                $this->jpushUser(1, $user_id, '您的订单，下单成功！', json([]));
            } catch (\Exception $e) {
                Log::record($e->getMessage(), 'error');
            }

            Db::commit();
            return json(['status' => 200, 'msg' => '下单成功', 'order' => $order]);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '下单失败']);
        }

    }


    public function payMoney()
    {
        extract(input());
        $order = explode(',', $order);
        $special = '';
        foreach ($order as $key => $vo) {
            $oo = Db::name('order')->where('o_order_num', $vo)->find();
            if ($oo['o_pay_status'] == 2) {
                unset($order[$key]);
            }
            if ($oo['o_m_type'] == 2) $special = 'One';
            if ($oo['o_type'] == 2) {
                $all_order = Db::name('order')->where(['o_type' => 2, 'o_shop_id' => $oo['o_shop_id'], 'o_status' => ['in', '2,3']])->select();
                $inte = Db::name('shop')->where('shop_id', $oo['o_shop_id'])->find();
                $must = 0;
                if (!empty($all_order)) {
                    foreach ($all_order as $vv) {
                        $pro = Db::name('order_info')->where('oi_order_id', $vv['o_id'])->select();
                        foreach ($pro as $z) {
                            $give = Db::name('product')->where(['p_id' => $z['oi_goods_id']])->value('p_give');
                            $must = $must + ($give * $z['oi_num']);
                        }
                    }
                }
                //这一块是积分押金不足的判断
//                if ($inte['shop_integral'] < $must) {
//                    Db::name('notice')->insert(['n_to' => 2, 'n_title' => '系统消息', 'n_content' => '积分押金不足，请尽快充值押金', 'n_images' => '', 'n_type' => 1, 'n_user_id' => $oo['o_shop_id'], 'n_read' => ',0,', 'n_delete' => ',0,', 'n_time' => date('Y-m-d H:i:s')]);
//
//                    $this->jpushShop(1, $oo['o_shop_id'], '积分押金不足，请尽快充值押金', json([]));
//
//                    if (count($order) == 1) {
//                        return json(['status' => 100, 'msg' => "商户赠送积分不足，暂不可支付"]);
//                    } else if (count($order) > 1) {
//                        unset($order[$key]);
//                    }
//                }
            }
        }
        if (empty($order)) {
            return json(['status' => 220, 'msg' => '支付成功']);
        }
        $order = implode(',', $order);

        $v = Db::name('order')->where(['o_order_num' => ['in', $order]])->field('SUM(o_money) AS o_money,SUM(o_jifen) AS o_jifen')->find();
        $cash = $v['o_money'];
        $jifen = $v['o_jifen'];
        $all = Db::name('jifen')->where(['jifen_user_id' => $user_id])->sum('jifen_number');
        if ($jifen > 0 && $jifen > $all) {
            return json(['status' => 100, 'msg' => '积分不足！']);
        }
        $num = Db::name('order')->where(['o_order_num' => ['in', $order]])->select();
        //----------------专门判断限购一份的 start -----------------
        $pidsForOne = Db::name('order_info')->alias('oi')
            ->join('order o','oi.oi_order_id = o.o_id')
            ->join('product p','oi.oi_goods_id = p.p_id')
            ->where('o_order_num', 'in',$order)
            ->where('p_buy_limit', 1)
            ->column('p_id');
        if($pidsForOne){
            $haveBuy = Db::name('order_info')->alias('oi')
                ->join('order o','oi.oi_order_id = o.o_id')
                ->where('o_user_id', $user_id)
                ->where('oi_goods_id', 'in',$pidsForOne)
                ->where('o_pay_status', 2)
                ->find();
            if($haveBuy) return json(['status' => 100, 'msg' => '限购一份，您已经购买过此商品了']);
        }
        //----------------专门判断限购一份的  end ------------------
        if ($jifen > 0 && $cash <= 0) {
            $rat = Db::name('jifen_conf')->where('conf_id', 2)->value('conf_rate');
            foreach ($num as $key => $vo) {
                $oi_goods_name = Db::name('order_info')->where('oi_order_id', $vo['o_id'])->column('oi_goods_name');
                if ($vo['o_jifen'] > 0) {
                    $back = $this->consume($user_id, $vo['o_jifen'], $vo['o_shop_id']);
                    if ($back['status'] == 100) {
                        return json($back);
                    } else {
                        Db::name('shop')->where('shop_id', $vo['o_shop_id'])->setInc('shop_balance_yet', $vo['o_jifen'] * $rat);
                    }

                    Db::name('jifen_consume')->insert(['consume_content' => '购买' . implode(',', $oi_goods_name) . '商品订单消费' . $vo['o_jifen'] . '积分', 'consume_user_id' => $user_id, 'consume_add_time' => date('Y-m-d H:i:s')]);
                }

                $cat = Db::name('order')->where('o_order_num', $vo['o_order_num'])->value('o_cate');

                $o_status = in_array($cat, [1, 3]) ? 2 : 10;

                Db::name('order')->where(['o_id' => $vo['o_id']])->update(['o_status' => $o_status, 'o_pay_status' => 2, 'o_pay_type' => 3]);

                $dec = Db::name('order_info')->where('oi_order_id', $vo['o_id'])->find();
                if ($dec['oi_goods_model']) {
                    Db::name('product_model')->where('m_id', $dec['oi_goods_model'])->setDec('m_num', $dec['oi_num']);
                } else {
                    Db::name('product')->where('p_id', $dec['oi_goods_id'])->setDec('p_stock_num', $dec['oi_num']);
                }
                Db::name('product')->where('p_id', $dec['oi_goods_id'])->setInc('p_sell_yet', $dec['oi_num']);

                Db::name('notice')->insert(['n_to' => 2, 'n_title' => '订单消息', 'n_content' => '您有新的订单~', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $vo['o_shop_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                try {
                    $this->sayMyName($vo['o_shop_id'],0,0,$vo['o_order_num'],3);
                    $this->jpushShop(1, $vo['o_shop_id'], '您有新的订单！', ['type2' => 1024, 'msg' => "您有一个新的线上订单"]);
                } catch (\Exception $e) {
                }

                Db::name('notice')->insert(['n_to' => 1, 'n_title' => '订单支付', 'n_content' => '购买' . implode(',', $oi_goods_name) . '商品订单支付成功，等待卖家处理', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $user_id, 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                try {
                    $this->jpushUser(1, $user_id, '订单支付成功，等待卖家处理', json([]));
                    $this->jpushDeviceShop($vo['o_shop_id'], '您有一个新的线上订单');
                } catch (\Exception $e) {
                }

            }

            return json(['status' => 220, 'msg' => '支付成功']);
        }
        if ($cash > 0) {
            if (isset($miniCode)) {
                $openid = $this->getOpenId($miniCode);
                if ($openid == '') {
                    return json(['status' => 100, 'msg' => '支付失败']);
                }
                Db::name('order')->where(['o_order_num' => ["in", $order]])->setField("o_pay_type", 2);
                $wx = new Wechat();
                $money = $cash;
                $obj = [
                    'attach'       => "payMoney" . $special,
                    'body'         => "订单支付",
                    'total_fee'    => $money * 100,
                    'out_trade_no' => $order,
                    'product_id'   => "",
                    'trade_type'   => "JSAPI",
                    'openid'       => $openid
                ];
                $res = $wx->WeChatPayReady($obj);
                return json(['status' => 200, 'msg' => $res]);
            }
            if ($type == 1) {
                Db::name('order')->where(['o_order_num' => ["in", $order]])->setField("o_pay_type", 1);
                $ali = new Ali();
                $res = $ali->getParam($order, $cash, 'payMoney' . $special, '订单支付');
            } else {
                Db::name('order')->where(['o_order_num' => ["in", $order]])->setField("o_pay_type", 2);
                $wx = new Weixin();
                $money = $cash;
                $obj = [
                    'attach'       => "payMoney" . $special,
                    'body'         => "订单支付",
                    'total_fee'    => $money * 100,
                    'out_trade_no' => $order,
                    'product_id'   => "",
                    'trade_type'   => "APP"
                ];
                $res = $wx->WeChatPayReady($obj);
            }
            return json(['status' => 200, 'msg' => $res]);
        }
    }


    public function getAddress()
    {
        extract(input());
        $data = Db::name('address d')
            ->join('area r', 'r.district_id = d.add_province', 'left')
            ->join('area c', 'c.district_id = d.add_city', 'left')
            ->join('area q', 'q.district_id = d.add_area', 'left')
            ->where(['add_user_id' => $user_id])
            ->field(['add_id', 'add_name', 'add_phone', 'r.district' => 'sheng', 'c.district' => 'shi', 'q.district' => 'qu', 'add_detail', 'add_default'])
            ->order('add_default desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function hotPost()
    {
        extract(input());
        $user_block = DB::name('posts_block')
            ->where(['block_user_id' => $user_id])
            ->column('block_post_id');
        $where = [
            'post_state' => 1,
            'p.post_id' => ['not in', $user_block]
        ];
        if(isset($live) && $live == 2) $where['post_live'] = 2;
        $data = Db::name('posts p')
            ->join('u_user u', 'u.user_id = p.post_user_id', 'left')
            ->join('shop s', 's.shop_id = u.user_shop_id', 'left')
            ->where($where)
            ->field('p.*,user_username,user_image,user_shop_id,user_level,shop_name,user_level2,user_city_man')
            ->page($page, 10)
            ->order('post_hot desc,post_add_time DESC')
            ->select();
        if (!empty($data)) {
            foreach ($data as $key => $vo) {
                if ($vo['post_share_post']) {
                    $share = Db::name("posts p")
                        ->join('u_user u', 'u.user_id = p.post_user_id', 'left')
                        ->where(['post_id' => $vo['post_share_post']])
                        ->field('p.*,user_username,user_image')
                        ->find();
                    if (empty($share)) {
                        $share = false;
                    }
                    $data[$key]['post_share_post'] = $share;
                }
                $comment = Db::name('posts_comment c')
                    ->join('u_user u', 'c.comment_user_id = u.user_id', 'left')
                    ->join('u_user uu', 'c.comtt_reply_user_id = uu.user_id', 'left')
                    ->where('comment_post_id', $vo['post_id'])
                    ->field(['comment_id', 'comment_post_id', 'comment_user_id', 'u.user_username' => 'user_name', 'comment_content', 'comment_time', 'comtt_reply_user_id', 'uu.user_username' => 'reply_user_name', 'comment_type', 'u.user_image'])
                    ->limit(3)
                    ->order('comment_time asc')
                    ->select();
                if (!empty($comment)) {
                    $data[$key]['comment'] = $comment;
                } else {
                    $data[$key]['comment'] = [];
                }
                $like = Db::name('posts_like')
                    ->where(['like_user_id' => $user_id, 'like_post_id' => $vo['post_id']])
                    ->find();
                if (!empty($like)) {
                    $data[$key]['is_like'] = true;
                } else {
                    $data[$key]['is_like'] = false;
                }
                $share = Db::name('posts_share')
                    ->where(['share_user_id' => $user_id, 'share_post_id' => $vo['post_id']])
                    ->find();
                if (!empty($share)) {
                    $data[$key]['is_share'] = true;
                } else {
                    $data[$key]['is_share'] = false;
                }
                $com = Db::name('posts_comment')->where(['comment_post_id' => $vo['post_id'], 'comment_user_id' => $user_id])->find();
                if (!empty($com)) {
                    $data[$key]['is_comment'] = true;
                } else {
                    $data[$key]['is_comment'] = false;
                }
                $give = Db::name('posts_give')->where(['give_user_id' => $user_id, 'give_post_id' => $vo['post_id']])->find();
                if (!empty($give)) {
                    $data[$key]['is_give'] = true;
                } else {
                    $data[$key]['is_give'] = false;
                }
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function nearbyPost()
    {
        extract(input());
        $user_block = DB::name('posts_block')
            ->where(['block_user_id' => $user_id])
            ->column('block_post_id');
        $where = [
            'post_state' => 1,
            'p.post_id' => ['not in', $user_block]
        ];
        if(isset($live) && $live == 2) $where['post_live'] = 2;
        $data = Db::name('posts p')
            ->join('u_user u', 'u.user_id = p.post_user_id', 'left')
            ->join('shop s', 's.shop_id = u.user_shop_id', 'left')
            ->where($where)
            ->field('p.*,user_username,user_shop_id,user_level,user_level2,user_city_man,shop_name,user_image,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((' . $lat . '* PI() / 180 - post_lat * PI() / 180) / 2),2) + COS(' . $lat . ' * PI() / 180) * COS(post_lat * PI() / 180) * POW(SIN((' . $lon . ' * PI() / 180 - post_lon * PI() / 180) / 2),2))),2) AS distance')
            ->page($page, 10)
            ->order('distance asc')
            ->select();
        if (!empty($data)) {
            foreach ($data as $key => $vo) {
                if ($vo['post_share_post']) {
                    $share = Db::name("posts p")
                        ->join('u_user u', 'u.user_id = p.post_user_id', 'left')
                        ->where(['post_id' => $vo['post_share_post']])
                        ->field('p.*,user_username,user_image')
                        ->find();
                    if (empty($share)) {
                        $share = false;
                    }
                    $data[$key]['post_share_post'] = $share;
                }
                $comment = Db::name('posts_comment c')
                    ->join('u_user u', 'c.comment_user_id = u.user_id', 'left')
                    ->join('u_user uu', 'c.comtt_reply_user_id = uu.user_id', 'left')
                    ->where('comment_post_id', $vo['post_id'])
                    ->field(['comment_id', 'comment_post_id', 'comment_user_id', 'u.user_username' => 'user_name', 'comment_content', 'comment_time', 'comtt_reply_user_id', 'uu.user_username' => 'reply_user_name', 'comment_type', 'u.user_image'])
                    ->limit(3)
                    ->order('comment_time asc')
                    ->select();
                if (!empty($comment)) {
                    $data[$key]['comment'] = $comment;
                } else {
                    $data[$key]['comment'] = [];
                }
                $like = Db::name('posts_like')
                    ->where(['like_user_id' => $user_id, 'like_post_id' => $vo['post_id']])
                    ->find();
                if (!empty($like)) {
                    $data[$key]['is_like'] = true;
                } else {
                    $data[$key]['is_like'] = false;
                }
                $share = Db::name('posts_share')
                    ->where(['share_user_id' => $user_id, 'share_post_id' => $vo['post_id']])
                    ->find();
                if (!empty($share)) {
                    $data[$key]['is_share'] = true;
                } else {
                    $data[$key]['is_share'] = false;
                }
                $com = Db::name('posts_comment')->where(['comment_post_id' => $vo['post_id'], 'comment_user_id' => $user_id])->find();
                if (!empty($com)) {
                    $data[$key]['is_comment'] = true;
                } else {
                    $data[$key]['is_comment'] = false;
                }
                $give = Db::name('posts_give')->where(['give_user_id' => $user_id, 'give_post_id' => $vo['post_id']])->find();
                if (!empty($give)) {
                    $data[$key]['is_give'] = true;
                } else {
                    $data[$key]['is_give'] = false;
                }
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function followPost()
    {
        extract(input());
        $fellow = Db::name('user_fellow')
            ->where(['fellow_user_id' => $user_id])
            ->column('fellow_star_user_id');
        $user_block = DB::name('posts_block')
            ->where(['block_user_id' => $user_id])
            ->column('block_post_id');
        $where = [
            'post_state' => 1,
            'p.post_id' => ['not in', $user_block]
        ];
        if(isset($live) && $live == 2) $where['post_live'] = 2;
        $data = Db::name('posts p')
            ->join('u_user u', 'u.user_id = p.post_user_id', 'left')
            ->join('shop s', 's.shop_id = u.user_shop_id', 'left')
            ->where(['post_user_id' => ['in', $fellow]])
            ->where($where)
            ->field('p.*,user_username,user_image,user_shop_id,user_level,user_level2,shop_name,user_city_man')
            ->page($page, 10)
            ->order('post_add_time desc')
            ->select();
        if (!empty($data)) {
            foreach ($data as $key => $vo) {
                if ($vo['post_share_post']) {
                    $share = Db::name("posts p")
                        ->join('u_user u', 'u.user_id = p.post_user_id', 'left')
                        ->where(['post_id' => $vo['post_share_post']])
                        ->field('p.*,user_username,user_image')
                        ->find();
                    if (empty($share)) {
                        $share = false;
                    }
                    $data[$key]['post_share_post'] = $share;
                }
                $comment = Db::name('posts_comment c')
                    ->join('u_user u', 'c.comment_user_id = u.user_id', 'left')
                    ->join('u_user uu', 'c.comtt_reply_user_id = uu.user_id', 'left')
                    ->where('comment_post_id', $vo['post_id'])
                    ->field(['comment_id', 'comment_post_id', 'comment_user_id', 'u.user_username' => 'user_name', 'comment_content', 'comment_time', 'comtt_reply_user_id', 'uu.user_username' => 'reply_user_name', 'comment_type', 'u.user_image'])
                    ->limit(3)
                    ->order('comment_time asc')
                    ->select();
                if (!empty($comment)) {
                    $data[$key]['comment'] = $comment;
                } else {
                    $data[$key]['comment'] = [];
                }
                $like = Db::name('posts_like')
                    ->where(['like_user_id' => $user_id, 'like_post_id' => $vo['post_id']])
                    ->find();
                if (!empty($like)) {
                    $data[$key]['is_like'] = true;
                } else {
                    $data[$key]['is_like'] = false;
                }
                $share = Db::name('posts_share')
                    ->where(['share_user_id' => $user_id, 'share_post_id' => $vo['post_id']])
                    ->find();
                if (!empty($share)) {
                    $data[$key]['is_share'] = true;
                } else {
                    $data[$key]['is_share'] = false;
                }
                $com = Db::name('posts_comment')->where(['comment_post_id' => $vo['post_id'], 'comment_user_id' => $user_id])->find();
                if (!empty($com)) {
                    $data[$key]['is_comment'] = true;
                } else {
                    $data[$key]['is_comment'] = false;
                }
                $give = Db::name('posts_give')->where(['give_user_id' => $user_id, 'give_post_id' => $vo['post_id']])->find();
                if (!empty($give)) {
                    $data[$key]['is_give'] = true;
                } else {
                    $data[$key]['is_give'] = false;
                }
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function likePost()
    {
        extract(input());
        $param = [
            'like_user_id' => $user_id,
            'like_post_id' => $post_id,
            'like_time'    => date('Y-m-d H:i:s')
        ];
        Db::startTrans();
        try {
            Db::name('posts_like')->insert($param);
            Db::name('posts')->where('post_id', $post_id)->inc('post_praise')->inc('post_hot')->update();
            Db::name('u_user')->where('user_id', $user_id)->setInc("user_zan");
            $post_user_id = DB::name('posts')->where('post_id', $post_id)->value('post_user_id');
            try {
                $this->jpushUser(1, $post_user_id, "有人点赞你的帖子", json([]));
            } catch (\Exception $e) {}
            Db::commit();
            return json(['status' => 200, 'msg' => '点赞成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '点赞失败']);
        }
    }


    public function unlikePost()
    {
        extract(input());
        $res = Db::name('posts_like')->where(['like_user_id' => $user_id, 'like_post_id' => $post_id])->delete();
        if ($res) {
            Db::name('posts')->where('post_id', $post_id)->dec('post_praise')->dec('post_hot')->update();
            Db::name('u_user')->where('user_id', $user_id)->setDec("user_zan");
            return json(['status' => 200, 'msg' => '取消点赞成功']);
        } else {
            return json(['status' => 100, 'msg' => '取消点赞失败']);
        }
    }


    public function blockPost()
    {
        extract(input());
        $param = [
            'block_user_id' => $user_id,
            'block_post_id' => $block_id,
            'block_time'    => date('Y-m-d H:i:s')
        ];
        $where['block_user_id'] = $user_id;
        $where['block_post_id'] = $block_id;
        $block = DB::name('posts_block')->where($where)->find();
        if ($block) {
            return json(['status' => 300, 'msg' => '您已屏蔽过该帖子']);
        } else {
            $res = Db::name('posts_block')->insert($param);
            if ($res) {
                return json(['status' => 200, 'msg' => '已屏蔽']);
            } else {
                return json(['status' => 100, 'msg' => '屏蔽失败']);
            }
        }
    }


    public function giveIntegral()
    {
        extract(input());
        if ($user_id == $he_id) {
            return json(['status' => 100, 'msg' => '不可打赏自己']);
        }
        if ($give <= 0) {
            return json(['status' => 100, 'msg' => '打赏金额不得低于0！']);
        }
        $cost = (int)$give;
        if ($cost <= 0) {
            return json(['status' => 100, 'msg' => '打赏金额有误！']);
        }

        Db::startTrans();
        try {
            $user = Db::name('u_user')->where('user_id', $user_id)->find();
            $he = Db::name('u_user')->where('user_id', $he_id)->find();
            $all = Db::name('jifen')->where(['jifen_user_id' => $user_id])->sum('jifen_number');
            $data = Db::name('jifen')->where(['jifen_user_id' => $user_id])->select();
            if ($all < $cost) {
                return json(['status' => 100, 'msg' => '积分不足']);
            }
            if ($all == $cost) {
                Db::name('jifen')->where(['jifen_user_id' => $user_id, 'jifen_id' => ['in', array_column($data, 'jifen_id')]])->setField('jifen_number', 0);
                foreach ($data as $key => $vo) {
                    $this->jifenFlow($vo['jifen_number'], $vo['jifen_from'], $he_id, 'giveIntegral');

                }
            }
            if ($all > $cost) {
                foreach ($data as $key => $vo) {
                    if ($cost != 0 && $vo['jifen_number'] != 0 && $vo['jifen_number'] == $cost) {
                        Db::name('jifen')->where(['jifen_id' => $vo['jifen_id']])->setField('jifen_number', 0);
                        $this->jifenFlow($vo['jifen_number'], $vo['jifen_from'], $he_id, 'giveIntegral');
                        break;
                    }
                    if ($cost != 0 && $vo['jifen_number'] != 0 && $vo['jifen_number'] > $cost) {
                        Db::name('jifen')->where(['jifen_id' => $vo['jifen_id']])->setField('jifen_number', $vo['jifen_number'] - $cost);
                        $this->jifenFlow($cost, $vo['jifen_from'], $he_id, 'giveIntegral');
                        break;
                    }
                    if ($cost != 0 && $vo['jifen_number'] != 0 && $vo['jifen_number'] < $cost) {
                        Db::name('jifen')->where(['jifen_id' => $vo['jifen_id']])->setField('jifen_number', 0);
                        $this->jifenFlow($vo['jifen_number'], $vo['jifen_from'], $he_id, 'giveIntegral');
                        $cost = $cost - $vo['jifen_number'];
                    }
                }
            }
            Db::name('jifen_consume')->insert(['consume_content' => '打赏给' . $he['user_username'] . '消费' . $give . '积分', 'consume_user_id' => $user_id, 'consume_add_time' => date('Y-m-d H:i:s')]);
            Db::name('jifen_consume')->insert(['consume_content' => $user['user_username'] . '打赏你' . $give . '积分', 'consume_user_id' => $he_id, 'consume_add_time' => date('Y-m-d H:i:s')]);
            $sum = Db::name('jifen')->where(['jifen_user_id' => $user_id])->sum('jifen_number');
            Db::name('u_user')->where('user_id', $user_id)->setField('user_integral', $sum);


            Db::name('notice')->insert(['n_to' => 1, 'n_title' => '打赏积分', 'n_content' => '打赏给' . $he['user_username'] . '消费' . $give . '积分', 'n_images' => '', 'n_type' => 3, 'n_user_id' => $user_id, 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
            try {
                $this->jpushUser(1, $user_id, '您打赏了' . $give . '积分', json([]));
            } catch (\Exception $e) {}
            Db::name('notice')->insert(['n_to' => 1, 'n_title' => '打赏积分', 'n_content' => $user['user_username'] . '打赏你' . $give . '积分', 'n_images' => '', 'n_type' => 3, 'n_user_id' => $he_id, 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
            try {
                $this->jpushUser(1, $he_id, '打赏获得' . $give . '积分', json([]));
            } catch (\Exception $e) {}
            Db::name('posts')->where('post_id', $post_id)->setInc('post_give', $give);
            Db::name('posts_give')->insert(['give_user_id' => $user_id, 'give_post_id' => $post_id, 'give_number' => $give, 'give_add_time' => date('Y-m-d H:i:s')]);
            Db::commit();
            return json(['status' => 200, 'msg' => '打赏成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '打赏失败']);
        }
    }


    public function newPost()
    {
        extract(input());
        if (isset($mini)) {
            $result = $this->msgSecCheck($content);
            if($result['code'] == 0){
                return json(['status' => 100, 'msg' => $result['msg']]);
            }
        }
        $user = Db::name('u_user')->where(['user_id' => $user_id])->find();
        if ($user['user_image'] == '' || preg_match("/^1[3456789]\d{9}$/", $user['user_username'])) {
            return json(['status' => 100, 'msg' => '发布动态需要先完善个人资料']);
        }
        $six = Db::name('posts')->where(['post_user_id' => $user_id])->whereTime('post_add_time', '-30 minutes')->count();
        if ($six > 0 && $user_id != 12) {
            return json(['status' => 100, 'msg' => '半小时后再发帖子']);
        }
        $param = [
            'post_type'       => $type,
            'post_content'    => $content,
            'post_link'       => $link,
            'post_user_id'    => $user_id,
            'post_share_post' => $share_id,
            'post_add_time'   => date('Y-m-d H:i:s'),
            'post_lon'        => $lon,
            'post_lat'        => $lat
        ];
        $can = getSSLFuck([$content]);
        if($can == false) return json(['status' => 100, 'msg' => '内容违规']);
        $res = Db::name('posts')->insertGetId($param);
        if ($res) {
            return json(['status' => 200, 'msg' => '发布成功', 'id' => $res]);
        } else {
            return json(['status' => 100, 'msg' => '发布失败', 'id' => '']);
        }
    }


    public function getComment()
    {
        header("Access-Control-Allow-Origin:*");
        extract(input());
        $data = Db::name('posts_comment c')
            ->join('u_user u', 'c.comment_user_id = u.user_id', 'left')
            ->join('u_user uu', 'c.comtt_reply_user_id = uu.user_id', 'left')
            ->where('comment_post_id', $post_id)
            ->field(['comment_id', 'comment_post_id', 'comment_user_id', 'u.user_username' => 'user_name', 'comment_content', 'comment_time', 'comtt_reply_user_id', 'uu.user_username' => 'reply_user_name', 'comment_type', 'u.user_image'])
            ->page($page, 10)
            ->order('comment_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function delPosts()
    {
        extract(input());
        $res = Db::name('posts')->where(['post_id' => $post_id])->setField('post_state', 3);
        if ($res) {
            return json(['status' => 200, 'msg' => '删除成功']);
        } else {
            return json(['status' => 100, 'msg' => '删除失败']);
        }
    }


    public function postComment()
    {
        extract(input());
        $result = $this->filterContent(1, $content);
        if ($result['status'] == 100) {
            return json($result);
        }
        $param = [
            'comment_post_id'     => $post_id,
            'comment_user_id'     => $user_id,
            'comment_content'     => $content,
            'comment_time'        => date('Y-m-d H:i:s'),
            'comment_type'        => $type,
            'comtt_reply_user_id' => $reply_id
        ];
        $res = Db::name('posts_comment')->insert($param);
        if ($res) {
            Db::name('posts')->where('post_id', $post_id)->inc('post_hot', 2)->inc('post_comment')->update();
            return json(['status' => 200, 'msg' => '评论成功']);
        } else {
            return json(['status' => 100, 'msg' => '评论失败']);
        }
    }

    /**
     * 过滤敏感词
     * @param $type
     * @param $content
     * @return array|\think\response\Json
     */
    public function filterContent($type, $content)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . config('mini.appId') . '&secret=' . config('mini.appSecret');
        $arr = https_request($url);
        $data = json_decode($arr, true);
        if (isset($data['errcode']) && 0 != $data['errcode']) {
            return json(['status' => 100, 'msg' => '系统错误']);
        }
        if (1 == $type) {//内容过滤
            $url1 = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $data['access_token'];
            $resault = https_request($url1, json_encode(['content' => $content], JSON_UNESCAPED_UNICODE), 'POST');
            $resaultArr = json_decode($resault, true);
            if (0 != $resaultArr['errcode']) {
                if (87014 == $resaultArr['errcode']) {
                    return ['status' => 100, 'msg' => '您的评论含敏感信息'];
                } else {
                    return ['status' => 100, 'msg' => '评论失败'];
                }
            } else {
                return ['status' => 200, 'msg' => 'ok'];
            }
        } else {//图片过滤
            $url1 = 'https://api.weixin.qq.com/wxa/img_sec_chec?access_token=' . $data['access_token'];
            $resault = https_request($url1, json_encode(['content' => $content], JSON_UNESCAPED_UNICODE), 'POST');
            dump($resault);
            die;
        }
    }


    public function postCenter()
    {
        extract(input());
        $user = Db::name('u_user')
            ->where(['user_id' => $he_id])
            ->field('user_id,user_username,user_image,user_level,user_level2,user_city_man,user_shop_id AS shop_name')
            ->find();
        $user['is_self'] = false;
        $user['is_focus'] = false;
        if ($user_id == $he_id) {
            $user['is_self'] = true;
        } else {
            $focus = Db::name('user_fellow')
                ->where(['fellow_user_id' => $user_id, 'fellow_star_user_id' => $he_id])
                ->find();
            if (!empty($focus)) {
                $user['is_focus'] = true;
            }
        }
        $user['posts'] = Db::name('posts')->where(['post_user_id' => $he_id, 'post_state' => 1])->count();
        $user['fellow'] = Db::name('user_fellow')->where(['fellow_user_id' => $he_id])->count();
        $user['fans'] = Db::name('user_fellow')->where(['fellow_star_user_id' => $he_id])->count();
        if ($user['shop_name']) {
            $user['shop_name'] = Db::name('shop')->where(['shop_id' => $user['shop_name']])->value('shop_name');
        }
        $user_block = DB::name('posts_block')
            ->where(['block_user_id' => $user_id])
            ->column('block_post_id');
        $data = Db::name('posts p')
            ->join('u_user u', 'u.user_id = p.post_user_id', 'left')
            ->join('shop s', 's.shop_id = u.user_shop_id', 'left')
            ->where(['post_state' => 1, 'post_user_id' => $he_id, 'p.post_id' => ['not in', $user_block]])
            ->field('p.*,user_username,user_image,user_shop_id,user_level,user_level2,shop_name,user_city_man')
            ->page($page, 10)
            ->order('post_add_time desc')
            ->select();
        if (!empty($data)) {
            foreach ($data as $key => $vo) {
                if ($vo['post_share_post']) {
                    $share = Db::name("posts p")
                        ->join('u_user u', 'u.user_id = p.post_user_id', 'left')
                        ->where(['post_id' => $vo['post_share_post']])
                        ->field('p.*,user_username,user_image')
                        ->find();
                    if (empty($share)) {
                        $share = false;
                    }
                    $data[$key]['post_share_post'] = $share;
                }
                $comment = Db::name('posts_comment c')
                    ->join('u_user u', 'c.comment_user_id = u.user_id', 'left')
                    ->join('u_user uu', 'c.comtt_reply_user_id = uu.user_id', 'left')
                    ->where('comment_post_id', $vo['post_id'])
                    ->field(['comment_id', 'comment_post_id', 'comment_user_id', 'u.user_username' => 'user_name', 'comment_content', 'comment_time', 'comtt_reply_user_id', 'uu.user_username' => 'reply_user_name', 'comment_type', 'u.user_image'])
                    ->limit(3)
                    ->order('comment_time asc')
                    ->select();
                if (!empty($comment)) {
                    $data[$key]['comment'] = $comment;
                } else {
                    $data[$key]['comment'] = [];
                }
                $like = Db::name('posts_like')
                    ->where(['like_user_id' => $user_id, 'like_post_id' => $vo['post_id']])
                    ->find();
                if (!empty($like)) {
                    $data[$key]['is_like'] = true;
                } else {
                    $data[$key]['is_like'] = false;
                }
                $share = Db::name('posts_share')
                    ->where(['share_user_id' => $user_id, 'share_post_id' => $vo['post_id']])
                    ->find();
                if (!empty($share)) {
                    $data[$key]['is_share'] = true;
                } else {
                    $data[$key]['is_share'] = false;
                }
                $com = Db::name('posts_comment')->where(['comment_post_id' => $vo['post_id'], 'comment_user_id' => $user_id])->find();
                if (!empty($com)) {
                    $data[$key]['is_comment'] = true;
                } else {
                    $data[$key]['is_comment'] = false;
                }
                $give = Db::name('posts_give')->where(['give_user_id' => $user_id, 'give_post_id' => $vo['post_id']])->find();
                if (!empty($give)) {
                    $data[$key]['is_give'] = true;
                } else {
                    $data[$key]['is_give'] = false;
                }
            }
        }
        return json(['status' => 200, 'msg' => ['data' => $data, 'user' => $user]]);
    }


    public function userCenetr()
    {
        extract(input());
        $data = Db::name('u_user')
            ->where('user_id', $user_id)
            ->find();
        if ($data['user_username'] == $data['user_phone']) {
            $data['user_username'] = '请设置你的昵称';
        }
        $data['posts'] = Db::name('posts')->where(['post_user_id' => $user_id, 'post_state' => 1])->count();
        $data['fellow'] = Db::name('user_fellow')->where(['fellow_user_id' => $user_id])->count();
        $data['fans'] = Db::name('user_fellow')->where(['fellow_star_user_id' => $user_id])->count();
        $data['shop_img'] = '';
        if ($data['user_one_pay'] == 3) {
            $data['shop_img'] = Db::name('shop')->where('shop_id', $data['user_shop_id'])->value('shop_img');
        }
        $address = Db::name('address d')
            ->join('area r', 'r.district_id = d.add_province', 'left')
            ->join('area c', 'c.district_id = d.add_city', 'left')
            ->join('area q', 'q.district_id = d.add_area', 'left')
            ->where(['add_user_id' => $user_id])
            ->field(['add_id', 'r.district' => 'sheng', 'c.district' => 'shi', 'q.district' => 'qu', 'add_detail', 'add_default'])
            ->order('add_default desc')
            ->find();
        $p = Db::name('partner')->where(['par_user_id' => $user_id, 'par_cancel' => 0])->find();
        if (!empty($p)) {
            $p['par_name'] = DB::name('partner_class')
                ->where(['class_id' => $p['par_class_id']])
                ->value('class_name');
            $partner = $p;
            // 原来的合伙人可以修改一次加入的时间
            if ($partner['par_add_time'] < '2020-03-18 00:00:00') {
                $partner['edittime'] = true;
            } else {
                $partner['edittime'] = false;
            }
        } else {
            $partner = false;
        }
        $qian = Db::name('admin')->where('area', $data['user_area'])->find();
        $sign = false;
        if (!empty($qian) && $qian['sign'] == 1) {
            $sign = true;
        }
        $data['address'] = $address;
        $jifen = Db::name('order')->where(['o_type' => 1, 'o_status' => 1, 'o_user_id' => $user_id])->count();
        $jifen1 = Db::name('order')->where(['o_type' => 1, 'o_status' => 2, 'o_user_id' => $user_id])->count();
        $jifen2 = Db::name('order')->where(['o_type' => 1, 'o_status' => 3, 'o_user_id' => $user_id])->count();
        $jifen3 = Db::name('order')->where(['o_type' => 1, 'o_status' => 10, 'o_user_id' => $user_id])->count();
        $jifen4 = Db::name('order')->where(['o_type' => 1, 'o_status' => 4, 'o_user_id' => $user_id])->count();

        $cash = Db::name('order')->where(['o_type' => 2, 'o_status' => 1, 'o_user_id' => $user_id])->count();
        $cash1 = Db::name('order')->where(['o_type' => 2, 'o_status' => 2, 'o_user_id' => $user_id])->count();
        $cash2 = Db::name('order')->where(['o_type' => 2, 'o_status' => 3, 'o_user_id' => $user_id])->count();
        $cash3 = Db::name('order')->where(['o_type' => 2, 'o_status' => 10, 'o_user_id' => $user_id])->count();
        $cash4 = Db::name('order')->where(['o_type' => 2, 'o_status' => 4, 'o_user_id' => $user_id])->count();
        $cash5 = Db::name('order')->where(['o_type' => 2, 'o_status' => 11, 'o_user_id' => $user_id])->count();

        $count = Db::name('notice')
            ->where(['n_to' => 1, 'n_type' => ['in', '1,4'], 'n_read' => ['not like', "%," . $user_id . ",%"]])
            ->count();
        $count1 = Db::name('notice')
            ->where(['n_to' => 1, 'n_type' => ['in', '2,3,5'], 'n_read' => 1])
            ->count();
        if ($count + $count1 > 99) {
            $msg = 99;
        } else {
            $msg = $count + $count1;
        }
        $data['jifen'] = ['jifen' => $jifen, 'jifen1' => $jifen1, 'jifen2' => $jifen2, 'jifen3' => $jifen3, 'jifen4' => $jifen4];
        $data['cash'] = ['cash' => $cash, 'cash1' => $cash1, 'cash2' => $cash2, 'cash3' => $cash3, 'cash4' => $cash4, 'cash5' => $cash5];
        $data['msg'] = $msg;
        $data['partner'] = $partner;
        $data['sign'] = $sign;
        $data['status'] = Db::name('u_user')->where('user_id', $user_id)->value('user_one_pay');
        return json(['status' => 200, 'msg' => $data]);
    }


    public function newAddress()
    {
        extract(input());
        $param = [
            'add_name'      => $name,
            'add_phone'     => $phone,
            'add_province'  => $province,
            'add_city'      => $city,
            'add_area'      => $area,
            'add_detail'    => $detail,
            'add_user_id'   => $user_id,
            'add_default'   => $default,
            'add_add_time'  => date('Y-m-d H:i:s'),
            'add_edit_time' => date('Y-m-d H:i:s')
        ];
        $can = getSSLFuck($param);
        if($can == false) return json(['status' => 100, 'msg' => '有填写不合规内容']);
        Db::startTrans();
        try {
            if ($default == 2) {
                Db::name('address')->where(['add_user_id' => $user_id, 'add_default' => 2])->setField('add_default', 1);
            }
            Db::name('address')->insert($param);
            Db::commit();
            return json(['status' => 200, 'msg' => '添加地址成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '添加地址失败']);
        }
    }


    public function editAddress()
    {
        extract(input());
        $param = [
            'add_name'      => $name,
            'add_phone'     => $phone,
            'add_province'  => $province,
            'add_city'      => $city,
            'add_area'      => $area,
            'add_detail'    => $detail,
            'add_default'   => $default,
            'add_edit_time' => date('Y-m-d H:i:s')
        ];
        $can = getSSLFuck($param);
        if($can == false) return json(['status' => 100, 'msg' => '有填写不合规内容']);
        Db::startTrans();
        try {
            if ($default == 2) {
                Db::name('address')->where(['add_user_id' => $user_id, 'add_default' => 2])->setField('add_default', 1);
            }
            Db::name('address')->where(['add_id' => $add_id])->update($param);
            Db::commit();
            return json(['status' => 200, 'msg' => '修改地址成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '修改地址失败']);
        }
    }


    public function editUserInfo()
    {
        extract(input());
        $param = [
            'user_edit_time' => date('Y-m-d H:i:s')
        ];
        // 修改前用户信息
        $old_user = DB::name('u_user')
            ->where(['user_id' => $user_id])
            ->field('user_id,user_image,user_username,user_edit_image,user_edit_username')
            ->find();
        if (isset($image)) {
            $param['user_image'] = $image;
            $param['user_edit_image'] = 1;
        }
        if (isset($username) && !empty($username) && $username != '请设置你的昵称') {
            $param['user_username'] = str_replace('请设置你的昵称', '', $username);
            if ($username != $old_user['user_username']) {
                $param['user_edit_username'] = 1;
            }
        }
        if (isset($sex)) {
            $param['user_gender'] = $sex;
        }
        if (isset($birthday)) {
            $param['user_birthday'] = $birthday ?: null;
        }
        $sss = $param;
        unset($sss['user_image']);
        $can = getSSLFuck($sss);
        if($can == false) return json(['status' => 100, 'msg' => '有填写不合规内容']);
        Db::startTrans();
        try {
            $res = Db::name('u_user')->where(['user_id' => $user_id])->update($param);
            if (!empty($res)) {
                // 修改后用户信息
                $now_user = DB::name('u_user')
                    ->where(['user_id' => $user_id])
                    ->field('user_id,user_edit_image,user_edit_username,user_recommend')
                    ->find();
                if ($old_user['user_edit_image'] != 1 || $old_user['user_edit_username'] != 1) {
                    if ($now_user['user_edit_image'] == 1 && $now_user['user_edit_username'] == 1) {
                        //如果邀请方是合伙人另外奖励
                        $is_partner = DB::name('partner')
                            ->where(['par_user_id' => $now_user['user_recommend'], 'par_cancel' => 0])
                            ->find();
                        if (!empty($is_partner)) {
                            // 该级别合伙人推荐粉丝奖励有效时间
                            $invite_days = DB::name('partner_class')
                                ->where(['class_id' => $is_partner['par_class_id']])
                                ->value('class_fans_days');
                            // 邀请粉丝每天不能超过100位，超过没有奖励
                            $fans_count = DB::name('u_user')
                                ->where(['user_recommend' => $now_user['user_recommend']])
                                ->whereTime('user_time', 'today')
                                ->count();
                            if ($fans_count < 100) {
                                if (time() < (strtotime($is_partner['par_add_time']) + 3600 * 24 * $invite_days)) {
                                    // 合伙人一段时间内粉丝修改头像昵称资料积分奖励
                                    $give_jifen = DB::name('partner_class')
                                        ->where(['class_id' => $is_partner['par_class_id']])
                                        ->value('class_fans_jifen_edi');
                                    $this->par_fans($user_id, 3, 0, $user_id);
                                    // DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请好友完善资料获得'.$give_jifen.'积分','consume_user_id'=>$is_partner['par_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                    // Db::name('notice')->insert (['n_to'=>1,'n_title'=>'邀请好友','n_content'=>'邀请好友获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$is_partner['par_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                                } else {
                                    $this->par_fans($user_id, 3, 0, $user_id);
                                }
                            } else {
                                // 添加提示
                                Db::name('notice')->insert(['n_to' => 1, 'n_title' => '合伙人邀请好友', 'n_content' => '当日邀请好友已达上限', 'n_images' => '', 'n_type' => 3, 'n_user_id' => $now_user['user_recommend'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s'), 'n_where_id' => '']);
                                try {
                                    $this->jpushUser(1, $now_user['user_recommend'], '当日邀请好友已达上限', json([]));
                                } catch (\Exception $e) {}
                            }
                        }
                    }
                }
                Db::commit();
                return json(['status' => 200, 'msg' => '修改成功']);
            }
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '修改失败']);
        }
    }


    public function changePhone()
    {
        extract(input());
        if ($code == '') {
            return json(['status' => 100, 'msg' => '请填写验证码']);
        }
        $phone_code = Db::name('phonecode')->where(['phone' => $phone, 'status' => 0, 'type' => 1])->find();
        if (empty($phone_code)) {
            return json(['status' => 100, 'msg' => '请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if ($diff >= 30 * 60) {
            return json(['status' => 100, 'msg' => '验证码已失效']);
        }
        if ($code != $phone_code['code']) {
            return json(['status' => 100, 'msg' => '验证码输入错误']);
        }
        if ($type == 1) {
            Db::name('phonecode')->where('phone', $phone)->setField('status', 1);
            return json(['status' => 200, 'msg' => '验证通过']);
        } else {
            Db::startTrans();
            try {
                Db::name('u_user')->where('user_id', $user_id)->setField('user_phone', $phone);
                Db::name('phonecode')->where('phone', $phone)->setField('status', 1);
                Db::commit();
                return json(['status' => 200, 'msg' => '修改成功']);
            } catch (\Exception $e) {
                Db::rollback();
                Log::record($e->getMessage(), 'error');
                return json(['status' => 100, 'msg' => '修改失败']);
            }
        }
    }

    public function changePhone1()
    {
        extract(input());
        if ($code == '') {
            return json(['status' => 100, 'msg' => '请填写验证码']);
        }
        $phone_code = Db::name('phonecode')->where(['phone' => $mobile, 'status' => 0, 'type' => 1])->find();
        if (empty($phone_code)) {
            return json(['status' => 100, 'msg' => '请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if ($diff >= 30 * 60) {
            return json(['status' => 100, 'msg' => '验证码已失效']);
        }
        if ($code != $phone_code['code']) {
            return json(['status' => 100, 'msg' => '验证码输入错误']);
        }
        Db::startTrans();
        try {
            Db::name('u_user')->where('user_id', $user_id)->setField('user_phone', $phone);
            Db::name('phonecode')->where('phone', $mobile)->setField('status', 1);
            Db::commit();
            return json(['status' => 200, 'msg' => '修改成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '修改失败']);
        }
    }


    public function myIncome()
    {
        extract(input());
        $place = Db::name('u_user')->where('user_id', $user_id)->value('user_area');
        $area = Db::name('area')->where('district_id', $place)->value('district');
        $pool = Db::name('admin')->where('area', $place)->find();
        $shop = Db::name('shop')->where('shop_qu_id', $place)->field('SUM(shop_integral) AS shop_integral')->find();
        $member_count = Db::name('u_user')->where('user_area', $place)->count();
        $new_count = Db::name('u_user')->where(['user_area' => $place])->whereTime('user_time', 'today')->count();
        $user = Db::name('u_user')->where('user_id', $user_id)->find();
        $jifen = Db::name('jifen')->where('jifen_from', $place)->sum('jifen_number');
        $midd = Db::name('d_jifen')->where(['co_from' => $place, 'co_status' => 1])->sum("co_jifen");
        $partner = Db::name('partner p')
            ->join('u_user u', 'u.user_id = p.par_user_id', 'left')
            ->where(['par_qu_id' => $place, 'par_cancel' => 0, 'par_class_level' => 3, 'par_status' => 2])
            ->field(['user_id', 'user_username', 'user_image', 'ROUND(user_my_income,2)' => 'user_my_income'])
            ->order('par_sort desc')
            ->limit($pool['partner'])
            ->select();
        $data = [
            'area'           => $area,
            'pool'           => $pool['pool'],
            'residue'        => $pool['integral'],
            'shop'           => $shop['shop_integral'],
            'user'           => $jifen + $midd,
            'member'         => $member_count,
            'new'            => $new_count,
            'today_jifen'    => $user['user_today_jifen'],
            'today_income'   => round($user['user_today_income'], 2),
            'partner_income' => round($user['user_partner_income'], 2),
            'my_income'      => round($user['user_my_income'], 2),
            'partner'        => $partner,
            'balance'        => $user['user_balance'],
            'balance_yet'    => $user['user_balance_yet']
        ];
        $all = $data['residue'] + $data['shop'] + $data['user'];
        if ($all != $data['pool']) {
            if ($all > $data['pool']) {
                Db::name('admin')->where('id', $pool['id'])->setDec('integral', ($all - $data['pool']));
                $data['residue'] = $data['residue'] - ($all - $data['pool']);
            } else if ($all < $pool['pool']) {
                Db::name('admin')->where('id', $pool['id'])->setInc('integral', ($data['pool'] - $all));
                $data['residue'] = $data['residue'] + ($data['pool'] - $all);
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function moneyInfo()
    {
        extract(input());
        $data = Db::name('u_user')->where('user_id', $user_id)->field('user_balance,user_balance_yet,user_money_balance,user_money_balance_yet')->find();
        $conf = Db::name('jifen_conf')->where(['conf_id' => ['in', '29,30']])->select();
        $conf[1]['conf_rate'] = $conf[1]['conf_rate'] * 100;
        return json(['status' => 200, 'msg' => $data, 'conf' => $conf]);
    }


    public function takeCash()
    {
        extract(input());
        if($real_name == '张秀平' || $real_name == '高兴兰'){
            return json(['status' => 100, 'msg' => '您的账号异常，不能提现，请联系管理员！']);
        }
//        if($type == 1){
//            return json(['status' => 100, 'msg' => '支付宝暂不支持提现，请提现到微信！']);
//        }
        if ($code == '') {
            return json(['status' => 100, 'msg' => '请填写验证码']);
        }
        $phone = Db::name('u_user')->where('user_id', $user_id)->value('user_phone');
        $phone_code = Db::name('phonecode')->where(['phone' => $phone, 'status' => 0, 'type' => 1])->find();
        if (empty($phone_code)) {
            return json(['status' => 100, 'msg' => '请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if ($diff >= 30 * 60) {
            return json(['status' => 100, 'msg' => '验证码已失效']);
        }
        if ($code != $phone_code['code']) {
            return json(['status' => 100, 'msg' => '验证码输入错误']);
        }
        $conf = Db::name('jifen_conf')->where(['conf_id' => ['in', '29,30,31']])->column('conf_rate');
        $user = Db::name('u_user')->where('user_id', $user_id)->find();
        if ($type == 2 && isset($openid) && $openid == '') {
            return json(['status' => 100, 'msg' => '缺少微信openid']);
        }
        if (!empty($sort) && $sort == 1) {
            if ($user['user_money_balance'] <= 0) {
                return json(['status' => 100, 'msg' => '可提现金额不足']);
            }
            if ($money > $user['user_money_balance']) {
                return json(['status' => 100, 'msg' => '提现金额大于可提现余额']);
            }
            if ($user['user_money_balance'] < $conf[0]) {
                return json(['status' => 100, 'msg' => '可提现金额低于最低提现金额']);
            }
        } else {
            if ($user['user_balance'] <= 0) {
                return json(['status' => 100, 'msg' => '可提现金额不足']);
            }
            if ($money > $user['user_balance']) {
                return json(['status' => 100, 'msg' => '提现金额大于可提现金额']);
            }
            if ($user['user_balance'] < $conf[0]) {
                return json(['status' => 100, 'msg' => '可提现金额低于最低提现金额']);
            }
        }
        if ($money > 500 && $type == 2) {
            return json(['status' => 100, 'msg' => '500元以上请使用支付宝提现']);
        }
        if ($money < $conf[0]) {
            return json(['status' => 100, 'msg' => '提现金额低于最低提现金额']);
        }
        $is_have = Db::name('order')->where(['o_type' => 3, 'o_user_id' => $user_id, 'o_tixian_status' => 1])->count();
        if ($is_have > 0) {
            return json(['status' => 100, 'msg' => '您有待审核提现']);
        }
        $is_have2 = Db::name('order')
            ->where(['o_type' => 3, 'o_user_id' => $user_id])
            ->whereTime('o_add_time', 'today')
            ->count();
        if ($is_have2 >= 2) {
            return json(['status' => 100, 'msg' => '一天只能提现两次']);
        }
		//----------超额判断（总额，一日500）-start---------
		$maxMoney = Db::name('order')
		->where(['o_type'=>3,'o_user_id'=>$user_id,'o_tixian_status'=>2,'o_pay_type'=>$type])
		->whereTime('o_add_time','today')
		->sum('o_money');
		if($maxMoney + $money > 5000) return json(['status'=>100,'msg'=>'每日总提现额度不得超过5000']);
		//-------------------end-----------------------------
        if ($user['user_tixian_time'] < date('Y-m-d')) {
            Db::name('u_user')->where('user_id', $user_id)->update(['user_tixian_money' => 0, 'user_edit_time' => date('Y-m-d H:i:s')]);
        }

        $number = $this->getOrderNumber();
        $new_money = $money - ($money * $conf[1]);
        $param = [
            'o_type'      => 3,
            'o_user_id'   => $user_id,
            'o_order_num' => $number,
            'o_money'     => $money,
            'o_account'   => $account,
            'o_real_name' => $real_name,
            'o_pay_type'  => $type,
            'o_add_time'  => date('Y-m-d H:i:s')
        ];
        $user['user_tixian_money'] = DB::name('u_user')
            ->where(['user_id' => $user_id])
            ->value('user_tixian_money');
        if (($user['user_tixian_money'] + $money) >= $conf[2]) {
            $param['o_tixian_status'] = 1;
            if ($type == 2) {
                $param['o_openid'] = $openid;
            }
            if (!empty($sort) && $sort == 1) {
                $param['o_sort'] = 1;
            }
            Db::name('order')->insert($param);
            return json(['status' => 200, 'msg' => '提现已申请，等待后台审核']);
        } else {
            if ($type == 1) {
                $ali = new Ali();
                $res = $ali->tixianAgreeShopOrWork($number, $new_money, $account, $real_name);
                $msg = '支付宝';
            } else {
                $wx = new Weixin();
                $res = $wx->userTiXian($number, $openid, $new_money, $real_name);
                $msg = '微信';
            }
            if ($res['status'] == 200) {
                $param['o_tixian_status'] = 2;
                $param['o_pay_status'] = 2;
                $param['o_third_order_num'] = $res['msg'];
                if (!empty($sort) && $sort == 1) {
                    $param['o_sort'] = 1;
                }
                Db::name('order')->insert($param);
                $update = ['user_tixian_time' => date('Y-m-d'), 'user_tixian_money' => ($user['user_tixian_money'] + $money)];
                if ($type == 1) {
                    $update['user_tx_account'] = $account;
                    $update['user_tx_relname'] = $real_name;
                    $update['user_tx_type'] = $type;
                } else {
                    $update['user_tx_account'] = $account;
                    $update['user_tx_openid'] = $openid;
                    $update['user_tx_relname'] = $real_name;
                    $update['user_tx_type'] = $type;
                }
                if (!empty($sort) && $sort == 1) {
                    Db::name('u_user')->where('user_id', $user_id)->dec('user_money_balance', $money)->inc('user_money_balance_yet', $money)->update($update);
                } else {
                    Db::name('u_user')->where('user_id', $user_id)->dec('user_balance', $money)->inc('user_balance_yet', $money)->update($update);
                }
                // Db::name('admin')->where('id',1)->setDec ('balance',$new_money);

                Db::name('notice')->insert(['n_to' => 1, 'n_title' => '余额提现', 'n_content' => '您提现了' . $money . '元' . "，已提现至您的{$msg}账户，请注意查收！", 'n_images' => '', 'n_type' => 3, 'n_user_id' => $user_id, 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                try {
                    $this->jpushUser(1, $user_id, '您提现了' . $money . '元' . "，已提现至您的{$msg}账户，请注意查收！", json([]));
                } catch (\Exception $e) {}
                return json(['status' => 200, 'msg' => "已提现至您的{$msg}账户，请注意查收！"]);
            } else {
                return json(['status' => 100, 'msg' => $res['msg']]);
            }
        }
    }


    public function takeCashList()
    {
        extract(input());
        $data = Db::name('order')
            ->where(['o_type' => 3, 'o_user_id' => $user_id])
            ->page($page, 10)
            ->order('o_add_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function getNoticeData()
    {
        extract(input());
        $s = new Shop();
        $data['system'] = $s->getNotice(1, 1, $user_id);
        $data['order'] = $s->getNotice(2, 1, $user_id);
        $data['active'] = $s->getNotice(4, 1, $user_id);
        $data['win'] = $s->getNotice(5, 1, $user_id);
        $data['momey'] = $s->getNotice(3, 1, $user_id);
        return json(['status' => 200, 'msg' => $data]);
    }


    public function getNoticeList()
    {
        extract(input());
        $where = [
            'n_to'   => 1,
            'n_type' => $type
        ];
        if (in_array($type, [1, 4])) {
            $where['n_delete'] = ['not like', "%," . $user_id . ",%"];
            $map = "n_user_id = '' OR n_user_id = " . $user_id;
        } elseif (in_array($type, [2, 3, 5])) {
            $where['n_user_id'] = $user_id;
            $where['n_delete'] = 1;
            $map = '';
        }
        $data = Db::name('notice')
            ->where($where)
            ->where($map)
            ->order('n_time desc')
            ->page($page, 10)
            ->select();
        if (!empty($data)) {
            foreach ($data as $key => $vo) {
                if (in_array($vo['n_type'], [1, 4])) {
                    $n_read = explode(',', $vo['n_read']);
                    if (in_array($user_id, $n_read)) {
                        $data[$key]['n_read'] = 2;
                    } else {
                        $data[$key]['n_read'] = 1;
                    }
                }
                if ($vo['n_type'] == 5 && $vo['n_where_id']) {
                    $data[$key]['n_where_id'] = Db::name('product')->where('p_id', $vo['n_where_id'])->value('p_name');
                }
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function getJifenOrder()
    {
        extract(input());
        $where = [
            'o_type'    => 1,
            'o_user_id' => $user_id
        ];
        switch ($type) {
            case 1:
                break;
            case 2:
                $where['o_status'] = 1;
                break;
            case 3:
                $where['o_status'] = 2;
                break;
            case 4:
                $where['o_status'] = 3;
                break;
            case 5:
                $where['o_status'] = 10;
                break;
            case 6:
                $where['o_status'] = 4;
                break;
            case 7:
                $where['o_status'] = 6;
                break;
        }
        $data = Db::name('order')
            ->where($where)
            ->page($page, 10)
            ->order('o_add_time desc')
            ->select();
        if (!empty($data)) {
            foreach ($data as $key => $vo) {
                $info = Db::name('order_info')
                    ->where(['oi_order_id' => $vo['o_id']])
                    ->select();
                $data[$key]['info'] = $info;
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function getCashOrder()
    {
        extract(input());
        $where = [
            'o_type'    => 2,
            'o_user_id' => $user_id
        ];
        switch ($type) {
            case 1:
                break;
            case 2:
                $where['o_status'] = 1;
                break;
            case 3:
                $where['o_status'] = 2;
                break;
            case 4:
                $where['o_status'] = 3;
                break;
            case 5:
                $where['o_status'] = 10;
                break;
            case 6:
                $where['o_status'] = 4;
                break;
            case 7:
                $where['o_status'] = 11;
                break;
        }
        $data = Db::name('order')
            ->where($where)
            ->page($page, 10)
            ->order('o_add_time desc')
            ->select();
        if (!empty($data)) {
            foreach ($data as $key => $vo) {
                $info = Db::name('order_info')
                    ->where(['oi_order_id' => $vo['o_id']])
                    ->select();
                $data[$key]['info'] = $info;
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function jifenInfo()
    {
        extract(input());
        $sum = Db::name('jifen')->where(['jifen_user_id' => $user_id])->sum('jifen_number');
        $list = Db::name('jifen_consume')
            ->where('consume_user_id', $user_id)
            ->page($page, 10)
            ->order('consume_add_time desc')
            ->select();
        return json(['status' => 200, 'msg' => ['integral' => $sum, 'list' => $list]]);
    }


    public function rechargeCard()
    {
        return json(['status' => 100, 'msg' => '充值失败']);
        extract(input());
        // $info = Db::name('card')->where('card_number',$number)->find();
        // if(empty($info)){
        // return json(['status'=>100,'msg'=>'卡号不存在']);
        // }
        // if($info['card_status'] == 2){
        // return json(['status'=>100,'msg'=>'此卡已被使用']);
        // }
        // if($info['card_password'] != md5($password)){
        // return json(['status'=>100,'msg'=>'密码错误']);
        // }
        // Db::startTrans ();
        // try{
        // $have = Db::name('admin')->where('area',$info['card_area'])->find();
        // $district = Db::name('area')->where('district_id',$info['card_area'])->value('district');
        // if($have['integral'] < $info['card_sum']){
        // return json(['status'=>100,'msg'=>"代理积分不足"]);
        // }
        // Db::name('admin')->where('area',$info['card_area'])->setDec ('integral',$info['card_sum']);


        // $this->jifenFlow($info['card_sum'],$info['card_area'],$user_id,'rechargeCard');
        // Db::name('jifen_consume')->insert(['consume_content'=>'积分充值'.$info['card_sum'].'积分('.$district.')','consume_user_id'=>$user_id,'consume_add_time'=>date('Y-m-d H:i:s')]);

        // Db::name('order')->insert(['o_type'=>6,'o_order_num'=>$this->getOrderNumber (),'o_recharge_type'=>1,'o_user_id'=>$user_id,'o_jifen'=>$info['card_sum'],'o_pay_status'=>2,'o_add_time'=>date('Y-m-d H:i:s')]);

        // Db::name('card')->where('card_number',$number)->setField ('card_status',2);
        // Db::name('notice')->insert (['n_to'=>1,'n_title'=>'积分充值','n_content'=>'您充值了'.$info['card_sum'].'积分('.$district.')','n_images'=>'','n_type'=>3,'n_user_id'=>$user_id,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
        // $this->jpushUser(1,$user_id,'您充值了'.$info['card_sum'].'积分('.$district.')',json([]));

        // Db::commit ();
        // return json(['status'=>200,'msg'=>'充值成功']);
        // }catch (\Exception $e){
        // Db::rollback ();
        // Log::record($e->getMessage(),'error');
        // return json(['status'=>100,'msg'=>'充值失败']);
        // }
    }


    public function getQrcodeJifen()
    {
        extract(input());
        if ($side == 2) {
            return json(['status' => 100, 'msg' => '不可扫描']);
        }
        $qrcode = Db::name('qrcode')->where('qr_id', $id)->find();
        if ($qrcode['qr_status'] == 2) {
            return json(['status' => 100, 'msg' => '二维码已使用']);
        }
        if ($qrcode['qr_status'] == 3) {
            return json(['status' => 100, 'msg' => '二维码已失效']);
        }
        $shop = Db::name('shop')->where('shop_id', $qrcode['qr_shop_id'])->find();
        if ($qrcode['qr_num'] > $shop['shop_integral']) {
            return json(['status' => 100, 'msg' => '赠送商户积分不足']);
        }
        Db::startTrans();
        try {
            $rat = Db::name('jifen_conf')->where('conf_id', 1)->value('conf_rate');

            Db::name('shop')->where('shop_id', $qrcode['qr_shop_id'])->dec('shop_integral', $qrcode['qr_num'])->dec('shop_pledge_money', $qrcode['qr_num'] * $rat)->update();

            $this->jifenFlow($qrcode['qr_num'], $shop['shop_qu_id'], $user_id, 'getQrcodeJifen');

            Db::name('notice')->insert(['n_to' => 1, 'n_title' => '积分赠送', 'n_content' => $shop['shop_name'] . "赠送你" . $qrcode['qr_num'] . "积分", 'n_images' => '', 'n_type' => 3, 'n_user_id' => $user_id, 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
            try {
                $this->jpushUser(1, $user_id, $shop['shop_name'] . "赠送你" . $qrcode['qr_num'] . "积分", json([]));
            } catch (\Exception $e) {}
            Db::name('jifen_consume')->insert(['consume_content' => $shop['shop_name'] . "赠送你" . $qrcode['qr_num'] . "积分", 'consume_user_id' => $user_id, 'consume_add_time' => date('Y-m-d H:i:s')]);

            Db::name('order')->insert(['o_type' => 7, 'o_order_num' => $this->getOrderNumber(), 'o_shop_id' => $qrcode['qr_shop_id'], 'o_user_id' => $user_id, 'o_jifen' => $qrcode['qr_num'], 'o_pay_status' => 2, 'o_add_time' => date('Y-m-d H:i:s')]);


            Db::name('qrcode')->where('qr_id', $id)->setField('qr_status', 2);

            Db::commit();
            return json(['status' => 200, 'msg' => '充值成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '充值失败']);
        }
    }


    public function collectList()
    {
        extract(input());
        if ($type == 1) {
            $join = 'product p';
            $condition = 'p.p_id = c.col_sp_id';
            $where = [
                'col_type'    => $type,
                'col_user_id' => $user_id
            ];
            $field = 'col_id,col_type,col_user_id,p_id,p_banner,p_name,p_content';
        } else {
            $join = 'shop s';
            $condition = 's.shop_id = c.col_sp_id';
            $where = [
                'col_type'    => $type,
                'col_user_id' => $user_id
            ];
            $field = 'col_id,col_type,col_user_id,shop_id,shop_name,shop_img,shop_introduce';
        }
        $data = Db::name('collect c')
            ->join($join, $condition, 'left')
            ->where($where)
            ->field($field)
            ->page($page, 10)
            ->order('col_add_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function payOne()
    {
        extract(input());
        $admin = Db::name('admin')->where('area', $qu)->find();
        if (empty($admin)) {
            return json(['status' => 100, 'msg' => '该区域暂无代理']);
        }
        $user = Db::name('u_user')->where('user_id', $user_id)->find();
        $ago = Db::name('shop')->where(['shop_attestation' => 2, 'shop_account' => $user['user_phone']])->find();
        if (!empty($ago)) {
            return json(['status' => 100, 'msg' => '该账户已注册商户端']);
        }
        $son = Db::name('shop')->where('shop_son', $user['user_phone'])->find();
        if (!empty($son)) {
            return json(['status' => 100, 'msg' => '该账户是子账户不可注册商户端']);
        }
        $order = $this->getOrderNumber();
        $param = [
            'o_type'       => 8,
            'o_user_id'    => $user_id,
            'o_order_num'  => $order,
            'o_money'      => 1,
            'o_status'     => 5,
            'o_pay_type'   => $type,
            'o_pay_status' => 1,
            'o_add_time'   => date('Y-m-d H:i:s')
        ];
        Db::name('order')->insert($param);
        if ($type == 1) {
            $ali = new Ali();
            $res = $ali->getParam($order, 1, 'payOne', '一元开店');
        } else {
            $wx = new Weixin();
            $money = 1;
            $obj = [
                'attach'       => "payOne",
                'body'         => "一元开店",
                'total_fee'    => $money * 100,
                'out_trade_no' => $order,
                'product_id'   => "",
                'trade_type'   => "APP"
            ];
            $res = $wx->WeChatPayReady($obj);
        }
        return json(['status' => 200, 'msg' => $res]);
    }


    public function checkTheOrder()
    {
        extract(input());
        $res = Db::name('u_user')->where('user_id', $user_id)->value('user_one_pay');
        return json(['status' => 200, 'msg' => $res]);
    }


    public function setUpShop()
    {
        return json(['status' => 100, 'msg' => '请关掉应用重新进入，如无效果请下载最新版~']);
        extract(input());
        $user = Db::name('u_user')->where('user_id', $user_id)->find();
        $admin = Db::name('admin')->where('area', $qu)->find();
        if (empty($admin)) {
            return json(['status' => 100, 'msg' => '当前区暂无代理' . $sheng . '>' . $city . '>'.$qu]);
        }
        $rand = rand(100000, 999999);
        $shop = [
            'shop_user_id'        => $user_id,
            'shop_account'        => $user['user_phone'],
            'shop_password'       => md5($rand),
            'shop_name'           => $name,
            'shop_range'          => $range,
            'shop_remark'         => $remark,
            'shop_contact'        => $contact,
            'shop_address'        => $address,
            'shop_hand_img'       => $hand_img,
            'shop_facade_img'     => $facade_img,
            'shop_ldentity_img'   => $ldentity_img,
            'shop_sheng_id'       => $sheng,
            'shop_city_id'        => $city,
            'shop_time'           => date('Y-m-d H:i:s'),
            'shop_qu_id'          => $qu,
            'shop_lon'            => $lon,
            'shop_lat'            => $lat,
            'shop_superior_agent' => $admin['id'],
            'shop_attestation'    => 3,
            'shop_rand'           => $rand,
        ];
        Db::startTrans();
        try {
            $yet = Db::name('shop')->where('shop_account', $user['user_phone'])->find();
            if (!empty($yet)) {
                Db::name('shop')->where('shop_id', $yet['shop_id'])->update($shop);
            } else {
                $id = Db::name('shop')->insertGetId($shop);
                Db::name('u_user')->where('user_id', $user_id)->setField('user_shop_id', $id);
            }
            Db::name('u_user')->where('user_id', $user_id)->update(['user_one_pay' => 4, 'user_edit_time' => date('Y-m-d H:i:s')]);
            Db::commit();
            return json(['status' => 200, 'msg' => '等待审核']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '提交失败']);
        }
    }


    public function checkShopInfo()
    {
        extract(input());
        $data = Db::name('shop s')
            ->join('area p', 'p.district_id = s.shop_sheng_id', 'left')
            ->join('area c', 'c.district_id = s.shop_sheng_id', 'left')
            ->join('area q', 'q.district_id = s.shop_sheng_id', 'left')
            ->where('shop_user_id', $user_id)
            ->field('shop_name,shop_range,shop_address,p.district as sheng,c.district as city,q.district as qu,shop_contact,shop_remark,shop_attestation,shop_hand_img,shop_facade_img,shop_ldentity_img')
            ->find();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function feedBack()
    {
        extract(input());
        $area = Db::name('u_user')->where('user_id', $user_id)->value('user_area');
        $param = [
            'f_type'     => 1,
            'f_content'  => $content,
            'f_images'   => $images,
            'f_phone'    => $phone,
            'f_user_id'  => $user_id,
            'f_area'     => $area,
            'f_add_time' => date('Y-m-d H:i:s')
        ];
        $res = Db::name('feedback')->insert($param);
        if ($res) {
            return json(['status' => 200, 'msg' => '反馈成功']);
        } else {
            return json(['status' => 200, 'msg' => '反馈失败']);
        }
    }


    public function helpInfo()
    {
        extract(input());
        $question = Db::name('question')->order('que_sort desc')->select();
        $info = Db::name('admin')->where('area', $qu)->find();
        if (empty($info)) {
            $pid = Db::name('area')->where('district_id', $qu)->value('pid');
            $info = Db::name('admin')->where('area', $pid)->find();
            if (empty($info)) {
                $info = Db::name('admin')->where('id', 1)->find();
            }
        }
        $data = [
            'question' => $question,
            'phone'    => $info['phone']
        ];
        return json(['status' => 200, 'msg' => $data]);
    }


    public function teamWork()
    {
        extract(input());
        $param = [
            't_content'  => $content,
            't_images'   => $images,
            't_phone'    => $phone,
            't_user_id'  => $user_id,
            't_add_time' => date('Y-m-d H:i:s')
        ];
        $res = Db::name('teamwork')->insert($param);
        if ($res) {
            return json(['status' => 200, 'msg' => '提交成功']);
        } else {
            return json(['status' => 100, 'msg' => '提交失败']);
        }
    }


    public function setPayPassword()
    {
        extract(input());
        if ($code == '') {
            return json(['status' => 100, 'msg' => '请填写验证码']);
        }
        $phone_code = Db::name('phonecode')->where(['phone' => $phone, 'status' => 0, 'type' => 1])->find();
        if (empty($phone_code)) {
            return json(['status' => 100, 'msg' => '请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if ($diff >= 30 * 60) {
            return json(['status' => 100, 'msg' => '验证码已失效']);
        }
        if ($code != $phone_code['code']) {
            return json(['status' => 100, 'msg' => '验证码输入错误']);
        }
        $res = Db::name('u_user')->where('user_id', $user_id)->setField('user_pay_password', md5($password));
        if ($res) {
            return json(['status' => 200, 'msg' => '设置成功']);
        } else {
            return json(['status' => 100, 'msg' => '设置失败']);
        }
    }


    public function checkPayPassword()
    {
        extract(input());
        $user = Db::name('u_user')->where('user_id', $user_id)->find();
        if ($user['user_pay_password'] == '') {
            return json(['status' => 110, 'msg' => '请先设置支付密码']);
        }
        if ($user['user_pay_password'] != md5($password)) {
            return json(['status' => 100, 'msg' => '密码错误']);
        } else {
            return json(['status' => 200, 'msg' => '密码正确']);
        }
    }


    public function cancelOrder()
    {
        extract(input());
        $res = Db::name('order')
            ->where(['o_id' => $o_id])
            ->setField('o_status', 12);
        if ($res) {
            return json(['status' => 200, 'msg' => '取消成功']);
        } else {
            return json(['status' => 100, 'msg' => '取消失败']);
        }
    }


    public function refundMoney()
    {
        extract(input());
        Db::startTrans();
        try {
            $order = Db::name('order')->where('o_id', $o_id)->find();
            $param = [
                'o_refund_reason'     => $reason,
                'o_refund_money'      => $order['o_money'],
                'o_refund_describe'   => $describe,
                'o_refund_imgs'       => $imgs,
                'o_refund_apply_time' => date('Y-m-d H:i:s'),
                'o_status'            => 11,
                'o_refund'            => 1
            ];
            Db::name('order')->where('o_id', $o_id)->update($param);
            Db::name('notice')->insert(['n_to' => 1, 'n_title' => '购物订单', 'n_content' => '订单退款\退货，申请成功', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $user_id, 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
            try {
                $this->jpushUser(1, $user_id, '订单退款\退货，申请成功', json([]));
            } catch (\Exception $e) {}
            Db::name('notice')->insert(['n_to' => 2, 'n_title' => '购物订单', 'n_content' => '新的退款\退货订单，等待处理', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $order['o_shop_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
            $this->jpushShop(1, $order['o_shop_id'], '新的退款\退货订单，等待处理', json([]));

            Db::commit();
            return json(['status' => 200, 'msg' => '申请成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '申请失败']);
        }
    }


    public function getRefundInfo()
    {
        extract(input());
        if ($type == 1) {
            $data = Db::name('order')->where('o_id', $o_id)->find();
            return json(['status' => 200, 'msg' => $data]);
        } else {
            $param = [
                'o_refund_express'      => $express,
                'o_refund_express_code' => $code,
                'o_refund_express_num'  => $num
            ];
            $res = Db::name('order')->where('o_id', $o_id)->update($param);
            if ($res) {
                return json(['status' => 200, 'msg' => '提交成功']);
            } else {
                return json(['status' => 100, 'msg' => '提交失败']);
            }
        }
    }


    public function confirmOrder()
    {
        extract(input());
        Db::startTrans();
        try {
            Db::name('order')->where(['o_id' => $o_id])->setField('o_status', 4);
            $order = Db::name('order')->where(['o_id' => $o_id])->find();

            if ($order['o_esp'] == 1) {
                $order_info = Db::name('order_info')->where('oi_order_id', $order['o_id'])->select();
                $rat = Db::name('jifen_conf')->where('conf_id', 1)->value('conf_rate');
                $redYajinAll = 0;
                foreach ($order_info as $ss) {
                    $give = Db::name('product')->where('p_id', $ss['oi_goods_id'])->find();
                    if ($give['p_give'] > 0) {
                        $qu = Db::name('shop')->where('shop_id', $give['p_shop_id'])->value('shop_qu_id');
                        Db::name('admin')->where('area',$qu)->setDec('integral',$give['p_give']);
                        $redYajin = ($give['p_give'] * $ss['oi_num']) * $rat;
                        $redYajinAll += $redYajin;
//                        Db::name('shop')->where('shop_id', $give['p_shop_id'])->dec('shop_integral', $give['p_give'] * $ss['oi_num'])->dec('shop_pledge_money', ($give['p_give'] * $ss['oi_num']) * $rat)->update();

//                        Db::name('order')->insert(['o_type' => 5, 'o_order_num' => $this->getOrderNumber(), 'o_money' => ($give['p_give'] * $ss['oi_num']) * $rat, 'o_jifen' => '', 'o_status' => 5, 'o_pay_status' => 2, 'o_shop_id' => $give['p_shop_id'], 'o_add_time' => date('Y-m-d H:i:s')]);

                        $this->jifenFlow($give['p_give'] * $ss['oi_num'], $qu, $order['o_user_id'], 'confirmOrder');

                        Db::name('jifen_consume')->insert(['consume_content' => '购买' . $give['p_name'] . '商品赠送' . $give['p_give'] * $ss['oi_num'] . '积分', 'consume_user_id' => $order['o_user_id'], 'consume_add_time' => date('Y-m-d H:i:s')]);

                        Db::name('notice')->insert(['n_to' => 1, 'n_title' => '购买商品', 'n_content' => '购买' . $give['p_name'] . '商品赠送' . $give['p_give'] * $ss['oi_num'] . '积分', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $order['o_user_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                        try {
                            $this->jpushUser(1, $order['o_user_id'], '购买' . $give['p_name'] . '商品赠送' . $give['p_give'] * $ss['oi_num'] . '积分', json([]));
                        } catch (\Exception $e) {}
                    }
                }
                if ($order['o_money'] > 0) {
                    if($redYajinAll > 0){
                        Db::name('order')->where(['o_id' => $o_id])->setField('o_m_yajin', $redYajinAll);
                    }
                    Db::name('shop')->where('shop_id', $order['o_shop_id'])->setInc('shop_balance', $order['o_money'] - $order['o_m_money']-$redYajinAll);
                    Db::name('shop')->where('shop_id', $order['o_shop_id'])->setInc('shop_all_balance', $order['o_money'] - $order['o_m_money']-$redYajinAll);
                    shopjiluerror($order['o_shop_id'],$order['o_money'] - $order['o_m_money']-$redYajinAll,1);
                    Db::name('shop')->where('shop_id', $order['o_shop_id'])->setDec('shop_balance_yet', $order['o_money'] - $order['o_m_money']);

                    // 店铺现金交易额
                    DB::name('shop')->where('shop_id', $order['o_shop_id'])->setInc('shop_money_balance', $order['o_money'] - $order['o_m_money']);
                    // 店铺当日现金交易额// 定时任务，每日0点清空
                    DB::name('shop')->where('shop_id', $order['o_shop_id'])->setInc('shop_today_balance', $order['o_money'] - $order['o_m_money']);
                    // 店铺现金交易1‰分红
                    $shop_user_id = DB::name('shop')
                        ->where('shop_id', $order['o_shop_id'])
                        ->value('shop_user_id');
                    $this->shop_profit($order['o_shop_id'], $shop_user_id, $order['o_money'], 3);

                    // Db::name('admin')->where('id',1)->setDec ('balance',$order['o_money']);
                }
                if ($order['o_jifen'] > 0) {
                    $rat = Db::name('jifen_conf')->where('conf_id', 2)->value('conf_rate');
                    Db::name('shop')->where('shop_id', $order['o_shop_id'])->setDec('shop_balance_yet', $order['o_jifen'] * $rat);
                    Db::name('shop')->where('shop_id', $order['o_shop_id'])->setInc('shop_balance', $order['o_jifen'] * $rat);
                    Db::name('shop')->where('shop_id', $order['o_shop_id'])->setInc('shop_all_balance', $order['o_jifen'] * $rat);
                    shopjiluerror($order['o_shop_id'],$order['o_jifen'] * $rat,2);
                }
            } else if ($order['o_esp'] == 2) {
                Db::name('shop')->where('shop_id', $order['o_shop_id'])->setInc('shop_balance', $order['o_esp_money']);
                Db::name('shop')->where('shop_id', $order['o_shop_id'])->setInc('shop_all_balance', $order['o_esp_money']);
                shopjiluerror($order['o_shop_id'],$order['o_esp_money'],3);
                Db::name('shop')->where('shop_id', $order['o_shop_id'])->setDec('shop_balance_yet', $order['o_esp_money']);
                // 店铺现金交易额
                DB::name('shop')->where('shop_id', $order['o_shop_id'])->setInc('shop_money_balance', $order['o_esp_money']);
                // 店铺当日现金交易额// 定时任务，每日0点清空
                DB::name('shop')->where('shop_id', $order['o_shop_id'])->setInc('shop_today_balance', $order['o_esp_money']);
                // 店铺现金交易1‰分红
                $shop_user_id = DB::name('shop')
                    ->where('shop_id', $order['o_shop_id'])
                    ->value('shop_user_id');
                $this->shop_profit($order['o_shop_id'], $shop_user_id, $order['o_esp_money'], 3);
            }
            $this->checkYetMoney($order['o_shop_id']);
            //---------------------------------产品池分佣结算 start ---------------------------------------------
            if ($order['o_m_type'] == 2) {
                $pool = Db::name('m_record')
                    ->where('record_order_number', $order['o_order_num'])
                    ->where('record_from_type', 'in', '4,3,7,8')
                    ->select();
                if ($pool) {
                    if ($order['o_m_user_id'] && $order['o_m_user_id'] > 0) {
                        $qu = Db::name('u_user')->where('user_id', $order['o_m_user_id'])->value('user_area');
                    }
                    foreach ($pool as $k => $v) {
                        if ($v['record_money'] > 0) {
                            Db::name('u_user')->where('user_id', $v['record_user_id'])->setInc('user_m_pool_money', $v['record_money']);
                        }
                        if ($v['record_jifen'] > 0) {
                            $this->jifenFlow($v['record_jifen'], $qu, $v['record_user_id'], 'poolFenYong');
                            $quname = Db::name('area')->where('district_id', $qu)->value('district');
                            $cc = [
                                '3' => '用户购买' . $give['p_name'] . '商品返佣',
                                '4' => '用户购买' . $give['p_name'] . '商品返佣',
                                '7' => $give['p_name'] . '商品团团赚团长奖励',
                                '8' => $give['p_name'] . '商品参与团团赚奖励',
                            ];
                            Db::name('jifen_consume')->insert(['consume_content' => $cc[$v['record_from_type']] . $v['record_jifen'] . "积分({$quname})", 'consume_user_id' => $v['record_user_id'], 'consume_add_time' => date('Y-m-d H:i:s')]);
                        }
                        //推送待定
//                        Db::name('jifen_consume')->insert(['consume_content'=>'购买产品池'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','consume_user_id'=>$order['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
//                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购买商品','n_content'=>'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
//                        $this->jpushUser(1,$order['o_user_id'],'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分',json([]));
                    }
                }
                Db::name('m_record')->where('record_order_number', $order['o_order_num'])->update([
                    'record_status'    => 2,
                    'record_sure_time' => date('Y-m-d H:i:s')
                ]);
            }
            //---------------------------------产品池分佣结算 end ---------------------------------------------

            Db::name('notice')->insert(['n_to' => 1, 'n_title' => '购物订单', 'n_content' => '订单收货成功，等待买家评价', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $order['o_user_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
            try {
                $this->jpushUser(1, $order['o_user_id'], '订单收货成功，等待买家评价', json([]));
            } catch (\Exception $e) {}
            Db::commit();
            return json(['status' => 200, 'msg' => '确认收货成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '确认收货失败']);
        }
    }


    public function orderDetail()
    {
        extract(input());
        $data = Db::name('order')
            ->where(['o_id' => $o_id])
            ->find();
        $goods = [];
        if (!empty($data)) {
            $goods = Db::name('order_info')
                ->where(['oi_order_id' => $data['o_id']])
                ->select();
        }
        $data['goods'] = $goods;
        return json(['status' => 200, 'msg' => $data]);
    }


    public function appraiseGoods()
    {
        extract(input());
        Db::startTrans();
        try {
            $data = Db::name('order_info')->where(['oi_order_id' => $o_id])->column('oi_goods_id');
            foreach ($data as $vo) {
                $p = [
                    'app_p_id'    => $vo,
                    'app_user_id' => $user_id,
                    'app_type'    => $type,
                    'app_content' => $content,
                    'app_imgs'    => $imgs,
                    'app_time'    => date('Y-m-d H:i:s')
                ];
                $param[] = $p;
            }
            Db::name('order')->where(['o_id' => $o_id])->setField('o_status', 5);
            Db::name('appraise')->insertAll($param);
            Db::commit();
            return json(['status' => 200, 'msg' => '评价成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '评价失败']);
        }
    }


    public function getSignList()
    {
        extract(input());
        $status = Db::name('admin')->where('area', $qu_id)->find();
        if ($status['sign'] == 2) {
            return json(['status' => 100, 'msg' => '不可签到']);
        }
        $timestamp = $this->mFristAndLast($y, $m);
        $data = Db::name('sign')
            ->where('sign_user_id', $user_id)
            ->whereTime('sign_time', 'between', [$timestamp['firstday'], $timestamp['lastday']])
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function mFristAndLast($y = "", $m = "")
    {
        if ($y == "") $y = date("Y");
        if ($m == "") $m = date("m");
        $m = sprintf("%02d", intval($m));
        $y = str_pad(intval($y), 4, "0", STR_PAD_RIGHT);

        $m > 12 || $m < 1 ? $m = 1 : $m = $m;
        $firstday = strtotime($y . $m . "01000000");
        $firstdaystr = date("Y-m-01", $firstday);
        $lastday = strtotime(date('Y-m-d 23:59:59', strtotime("$firstdaystr +1 month -1 day")));

        return array(
            "firstday" => $firstday,
            "lastday"  => $lastday
        );
    }


    public function sign()
    {
        extract(input());
        $users = Db::name('u_user')->where('user_id', $user_id)->find();
        $status = Db::name('admin')->where('area', $users['user_area'])->find();
        if ($status['sign'] == 2) {
            return json(['status' => 100, 'msg' => '暂未开通签到']);
        }
        $today = Db::name('sign')->whereTime('sign_time', 'today')->where('sign_user_id', $user_id)->find();
        if (!empty($today)) {
            return json(['status' => 100, 'msg' => '今天已签到']);
        }
        Db::startTrans();
        try {
            $yesterday = Db::name('sign')->whereTime('sign_time', 'yesterday')->where('sign_user_id', $user_id)->find();
            if (empty($yesterday)) {
                Db::name('sign')->where('sign_user_id', $user_id)->delete();
            }
            $res = Db::name('sign')->insert(['sign_user_id' => $user_id, 'sign_time' => date('Y-m-d')]);
            $count = Db::name('sign')->where('sign_user_id', $user_id)->count();
            $get = Db::name('sign_prize')->where(['s_day' => $count])->find();
            if (!empty($get)) {
                if ($get['s_type'] == 1) {
                    Db::name('admin')->where('area', $users['user_area'])->setDec('integral', $get['s_num']);
                    $this->jifenFlow($get['s_num'], $users['user_area'], $user_id, 'sign');
                    Db::name('jifen_consume')->insert(['consume_content' => '签到获得' . $get['s_num'] . '积分', 'consume_user_id' => $user_id, 'consume_add_time' => date('Y-m-d H:i:s')]);
                } else {
                    $name = Db::name('product p')
                        ->join('shop s', 's.shop_id = p.p_shop_id', 'left')
                        ->where('p_id', $get['s_goods_id'])
                        ->find();
                    $addr = Db::name('address a')
                        ->join('area s', 's.district_id = a.add_province', 'left')
                        ->join('area c', 'c.district_id = a.add_city', 'left')
                        ->join('area q', 'q.district_id = a.add_area', 'left')
                        ->where('add_user_id', $user_id)
                        ->field('a.*,s.district sheng,c.district shi,q.district qu')
                        ->find();
                    $j_order_num = $this->getOrderNumber();
                    $order_for = [
                        'o_type'       => 2,
                        'o_user_id'    => $user_id,
                        'o_order_num'  => $j_order_num,
                        'o_money'      => $name['p_now_price'],
                        'o_status'     => $name['p_deliver_cate'] == 1 ? 2 : 10,
                        'o_pay_status' => 2,
                        'o_shop_id'    => $name['p_shop_id'],
                        'o_shop_name'  => $name['shop_name'],
                        'o_esp'        => 4,
                        'o_add_time'   => date('Y-m-d H:i:s')
                    ];
                    if (!empty($addr)) {
                        $order_for['o_name'] = $addr['add_name'];
                        $order_for['o_phone'] = $addr['add_phone'];
                        $order_for['o_address'] = $addr['sheng'] . $addr['shi'] . $addr['qu'] . $addr['add_detail'];
                    }
                    if ($name['p_deliver_cate'] == 1 || $name['p_deliver_cate'] == 3) {
                        $order_for['o_cate'] = 1;
                    } else {
                        $order_for['o_qrcode'] = http_type() . "/api/shop/scanQrcodeOrder?num=" . $j_order_num;
                        $order_for['o_cate'] = $name['p_deliver_cate'];
                    }
                    $j_get_id = Db::name('order')->insertGetId($order_for);
                    $info_for = [
                        'oi_order_id'    => $j_get_id,
                        'oi_goods_id'    => $name['p_id'],
                        'oi_goods_name'  => $name['p_name'],
                        'oi_goods_image' => $name['p_banner'],
                        'oi_goods_price' => $name['p_now_price'],
                        'oi_goods_jifen' => 0,
                        'oi_goods_model' => '',
                        'oi_num'         => 1,
                        'oi_total_price' => $name['p_now_price'],
                        'oi_total_jifen' => 0
                    ];
                    Db::name('order_info')->insert($info_for);
                }
                $param = [
                    'n_to'      => 1,
                    'n_title'   => '签到奖励',
                    'n_content' => "签到获得：{$get['s_name']}",
                    'n_type'    => 1,
                    'n_user_id' => $user_id,
                    'n_read'    => ',0,',
                    'n_delete'  => ',0,',
                    'n_time'    => date('Y-m-d H:i:s')
                ];
                Db::name('notice')->insert($param);
                try {
                    $this->jpushUser(1, $user_id, "签到获得：{$get['s_name']}", json([]));
                } catch (\Exception $e) {}
            }
            Db::commit();
            return json(['status' => 200, 'msg' => '签到成功', 'data' => isset($get['s_name']) ? $get['s_name'] : '']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '签到失败']);
        }
    }


    public function myFriendList()
    {
        extract(input());
        $data = Db::name('user_fellow f')
            ->join('u_user u', 'u.user_id = f.fellow_star_user_id', 'left')
            ->where(['fellow_user_id' => $user_id])
            ->field('user_id,user_username,user_image')
            ->order('fellow_add_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function fansList()
    {
        extract(input());
        $data = Db::name('user_fellow f')
            ->join('u_user u', 'u.user_id = f.fellow_user_id', 'left')
            ->where(['fellow_star_user_id' => $he_id])
            ->field("user_id,user_username,user_image")
            ->order('fellow_add_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function fellowList()
    {
        extract(input());
        $data = Db::name('user_fellow f')
            ->join('u_user u', 'u.user_id = f.fellow_star_user_id', 'left')
            ->where(['fellow_user_id' => $he_id])
            ->field('user_id,user_username,user_image')
            ->order('fellow_add_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function addFriend()
    {
        extract(input());
        $focus = Db::name('user_fellow')->where(['fellow_user_id' => $user_id, 'fellow_star_user_id' => $he_id])->find();
        if (!empty($focus)) {
            return json(['status' => 100, 'msg' => '已关注该好友']);
        }
        $time = date('Y-m-d H:i:s');
        $param = [
            [
                'fellow_user_id'      => $user_id,
                'fellow_star_user_id' => $he_id,
                'fellow_add_time'     => $time
            ],
            [
                'fellow_user_id'      => $he_id,
                'fellow_star_user_id' => $user_id,
                'fellow_add_time'     => $time
            ]
        ];
        $res = Db::name('user_fellow')->insertAll($param);
        if ($res) {
            Db::name('u_user')->where('user_id', $he_id)->setInc('user_fans');
            Db::name('u_user')->where('user_id', $user_id)->setInc('user_attention');
            return json(['status' => 200, 'msg' => '加好友成功']);
        } else {
            return json(['status' => 100, 'msg' => '加好友失败']);
        }
    }


    public function deleteFriend()
    {
        extract(input());
        $res = Db::name('user_fellow')
            ->where("(`fellow_user_id` = {$user_id} AND `fellow_star_user_id` = {$he_id}) OR (`fellow_user_id` = {$he_id} AND `fellow_star_user_id` = {$user_id})")
            ->delete();
        if ($res) {
            Db::name('u_user')->where('user_id', $he_id)->setDec('user_fans');
            Db::name('u_user')->where('user_id', $user_id)->setDec('user_attention');
            return json(['code' => 200, 'msg' => '取消关注成功']);
        } else {
            return json(['code' => 100, 'msg' => '取消关注失败']);
        }
    }


    public function getDefaultAddr()
    {
        extract(input());
        $def = Db::name('address d')
            ->join('area s', 's.district_id = d.add_province', 'left')
            ->join('area c', 'c.district_id = d.add_city', 'left')
            ->join('area q', 'q.district_id = d.add_area', 'left')
            ->where(['add_user_id' => $user_id, 'add_default' => 2])
            ->field('d.*,s.district sheng,c.district shi,q.district qu')
            ->find();
        if (empty($def)) {
            return json(['status' => 100, 'msg' => '无默认地址']);
        }
        return json(['status' => 200, 'msg' => $def]);
    }

    public function delAddr()
    {
        extract(input());
        $res = Db::name('address')->where('add_id', $add_id)->delete();
        if ($res) {
            return json(['status' => 200, 'msg' => '删除成功']);
        } else {
            return json(['status' => 100, 'msg' => '删除失败']);
        }
    }


    public function gameInfo()
    {
        extract(input());
        if ($type == 1) {
            $data = Db::name('d_join d')
                ->join('u_user u', 'u.user_id = d.j_user_id', 'left')
                ->field('user_id,user_image')
                ->order('j_join_time desc')
                ->select();
            $count = Db::name('d_join d')
                ->join('u_user u', 'u.user_id = d.j_user_id', 'left')
                ->count();
        } else {
            $data = Db::name('c_join')
                ->order('c_add_time desc')
                ->select();
            $count = Db::name('c_join')->count();
        }
        return json(['status' => 200, 'msg' => ['data' => $data, 'count' => $count]]);
    }


    public function getImgs()
    {
        extract(input());
        $data = Db::name('imgs')->limit(8)->select();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function reportPost()
    {
        extract(input());
        $param = [
            'report_post_id'  => $post_id,
            'report_user_id'  => $user_id,
            'report_add_time' => date('Y-m-d H:i:s')
        ];
        $res = Db::name('report')->insert($param);
        if ($res) {
            return json(['status' => 200, 'msg' => "举报成功"]);
        } else {
            return json(['status' => 100, 'msg' => "举报失败"]);
        }
    }


    public function postDetail()
    {
        header("Access-Control-Allow-Origin:*");
        extract(input());
        $data = Db::name('posts p')
            ->join('u_user u', 'u.user_id = p.post_user_id', 'left')
            ->where('post_id', $post_id)
            ->find();
        if (!empty($data)) {
            if ($data['user_shop_id']) {
                $data['shop_name'] = Db::name('shop')->where('shop_id', $data['user_shop_id'])->value('shop_name');
            }
            if ($data['post_share_post']) {
                $share = Db::name("posts p")
                    ->join('u_user u', 'u.user_id = p.post_user_id', 'left')
                    ->where(['post_id' => $data['post_share_post']])
                    ->find();
                if (empty($share)) {
                    $share = false;
                }
                $data['post_share_post'] = $share;
            }
            $like = Db::name('posts_like')
                ->where(['like_user_id' => $user_id, 'like_post_id' => $data['post_id']])
                ->find();
            if (!empty($like)) {
                $data['is_like'] = true;
            } else {
                $data['is_like'] = false;
            }
            $share = Db::name('posts_share')
                ->where(['share_user_id' => $user_id, 'share_post_id' => $data['post_id']])
                ->find();
            if (!empty($share)) {
                $data['is_share'] = true;
            } else {
                $data['is_share'] = false;
            }
            $com = Db::name('posts_comment')->where(['comment_post_id' => $data['post_id'], 'comment_user_id' => $user_id])->find();
            if (!empty($com)) {
                $data['is_comment'] = true;
            } else {
                $data['is_comment'] = false;
            }
            $give = Db::name('posts_give')->where(['give_user_id' => $user_id, 'give_post_id' => $data['post_id']])->find();
            if (!empty($give)) {
                $data['is_give'] = true;
            } else {
                $data['is_give'] = false;
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }


    public function setPostInc()
    {
        extract(input());
        Db::startTrans();
        try {
            Db::name('posts')->where('post_id', $post_id)->inc('post_hot', 3)->inc('post_share')->update();
            Db::name('posts_share')->insert(['share_post_id' => $post_id, 'share_user_id' => $user_id]);
            Db::commit();
            return json(['status' => 200, 'msg' => '转发成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => '转发失败']);
        }
    }


    public function getConfig()
    {
        extract(input());
        $data = Db::name('jifen_conf')->where(['conf_id' => $conf_id])->find();
        return json(['status' => 200, 'msg' => $data]);
    }


    public function createInviteCode()
    {
        extract(input());
        $user = Db::name('u_user')->where('user_id', $user_id)->find();
        if ($user['user_invite_code']) {
            return json(['status' => 200, 'msg' => $user['user_invite_code']]);
        } else {
            $invite = GetRandCode(6);
            $form = Db::name('u_user')->where('user_invite_code', $invite)->find();
            if (!empty($form)) {
                $this->createInviteCode();
            } else {
                Db::name('u_user')->where('user_id', $user_id)->setField('user_invite_code', $invite);
                return json(['status' => 200, 'msg' => $invite]);
            }
        }
    }
    public function createInviteCodeInside($user_id)
    {
        $user = Db::name('u_user')->where('user_id', $user_id)->find();
        if ($user['user_invite_code']) {
            return true;
        } else {
            $invite = GetRandCode(6);
            $form = Db::name('u_user')->where('user_invite_code', $invite)->find();
            if (!empty($form)) {
                $this->createInviteCodeInside($user_id);
            } else {
                Db::name('u_user')->where('user_id', $user_id)->setField('user_invite_code', $invite);
                return true;
            }
        }
    }


    /*******************************************二次开发******************************************/
    public function QRcodePay()
    {
        extract(input());
        if($type == 1) return json(['code' => 100,'status' => 100, 'msg' => '此功能优化升级中，请直接用微信或者支付宝扫码付款！']);
        $uid = '';
        $uname = '';
        $title = '';
        $image = '';
        $real_pay = '';
        $red_give = '';
        $shop_id = $this->encrypt($encrypt, 'DECODE');
        $shop = Db::name('shop')->where(['shop_id' => $shop_id])->find();
        if (!$shop_id || empty($shop)) {
            return json(['code' => 100, 'msg' => '收款码错误']);
        }
        if (!$user_id || $type == '') {
            return json(['code' => 100, 'msg' => '参数错误，请刷新页面']);
        }
        Db::startTrans();
        try {
            $order = $this->getOrderNumber();
            $param = [
                'record_number'       => $order,
                'record_user_id'      => $user_id,
                'record_shop_id'      => $shop_id,
                'record_type'         => $type,
                'record_payment_type' => $payment_type,
                'record_status'       => 1,
                'record_jifen'        => $integral,
                'record_money'        => $money,
                'record_remark'       => $remark,
                'record_add_time'     => date("Y-m-d H:i:s"),
                'record_give_jifen'   => 0,
                'record_lose_time'    => date("Y-m-d H:i:s", strtotime("+15 minutes"))
            ];
            if ($type == 1 && $money != '') {
                $conf_rate = Db::name('jifen_conf')->where('conf_id', 1)->value('conf_rate');
                $shop_ratio = DB::name('shop')->where('shop_id', $shop_id)->value('shop_ratio');
                if (!empty($shop_ratio)) {
                    $ratio = (10 - $shop_ratio) / 10;
                    $param['record_give_jifen'] = ($money * $ratio) / $conf_rate;
                } else {
                    $rule = Db::name('record_rule')->where(['rule_shop_id' => $shop_id])->order("rule_cash DESC")->select();
                    if (!empty($rule)) {
                        $ruleForCash = array_column($rule, 'rule_cash');
                        $ruleForIntegral = array_column($rule, 'rule_jifen');
                        foreach ($ruleForCash as $key => $vo) {
                            if ($money >= $vo) {
                                $param['record_give_jifen'] = $ruleForIntegral[$key];
                                break;
                            }
                        }
                    }
                }
            }
            $record_id = Db::name('record')->insertGetId($param);
            if ($type == 1) {
//                if ($param['record_give_jifen'] > 0) {
//                    $stay = Db::name('record')->where(['record_id' => ['neq', $record_id], 'record_type' => 1, 'record_status' => 1, 'record_shop_id' => $shop_id])->sum('record_give_jifen');
//                    if ($param['record_give_jifen'] > $shop['shop_integral'] - $stay) {
//                        try {
//                            $this->jpushShop(1, $shop_id, '您的店铺积分不足', json([]));
//                        } catch (\Exception $e) {
//                            Log::record($e->getMessage(), 'error');
//                        }
//                        Db::name('notice')->insert(['n_to' => 2, 'n_title' => '积分提醒', 'n_content' => '您的店铺积分不足', 'n_images' => '', 'n_type' => 1, 'n_user_id' => $shop_id, 'n_read' => ',0,', 'n_delete' => ',0,', 'n_time' => date('Y-m-d H:i:s')]);//消息
//                        return json(['status' => 100, 'msg' => '商家积分不足']);
//                    }
//                }
                //-----------------------------算红包start--------------------------------------
                if($shop['shop_qu_id']){
                    //1、先纠正一下
                    $time = time();
                    $one_hour_ago = date("Y-m-d H:i:s", ($time - 300));
                    Db::name('m_red_user')
                        ->where('ru_user_id','>',0)
                        ->where('ru_status',1)
                        ->where('ru_get_time','<=',$one_hour_ago)
                        ->setField('ru_user_id',0);
                    //2、找一个红包并赋值(先筛除一天一区领一个，且如果标中未支付，则还是这个)
                    $where = [
                        'red_user_id' => ['>',0]
                    ];
                    $whereNo = Db::name('m_red_user')
                        ->where('ru_user_id',$user_id)
                        ->where('ru_status',2)
                        ->whereTime('ru_get_time','today')
                        ->group('ru_red_id')
                        ->column('ru_red_id');
                    if($whereNo){
                        $whereRed = Db::name('m_red')
                            ->where('red_user_area',$shop['shop_qu_id'])
                            ->where('red_status',2)
                            ->where('red_id','in',$whereNo)
                            ->column('red_user_id');
                        if($whereRed){
                            $where = [
                                'red_user_id' => ['not in',$whereRed]
                            ];
                        }
                    }
                    $redData = Db::name('m_red r')
                        ->join('m_red_user ru','r.red_id = ru.ru_red_id','left')
                        ->where(['red_status' => 2 ,'ru_user_id' => $user_id,'red_user_area' => $shop['shop_qu_id']])
                        ->where('ru_status',1)
                        ->where($where)
                        ->where('ru_money','<',$money)
                        ->find();
                    if(!$redData) {
                        $redData = Db::name('m_red r')
                            ->join('m_red_user ru', 'r.red_id = ru.ru_red_id', 'left')
                            ->where(['red_status' => 2, 'ru_user_id' => 0, 'red_user_area' => $shop['shop_qu_id']])
                            ->where('ru_money', '<', $money)
                            ->where($where)
                            ->order('red_add_time desc')
                            ->find();
                    }
                    if($redData){
                        $hehuoData = Db::name('u_user')
                            ->where(['user_id' => $redData['red_user_id']])
                            ->field('user_username,user_phone,user_m_name')
                            ->find();
                        if($hehuoData['user_username'] == $hehuoData['user_phone']){
                            $hehuoData['user_username'] = substr($hehuoData['user_username'],0,3) . '****' . substr($hehuoData['user_username'],7,4);
                        }
                        $uid = $redData['red_user_id'];
                        $uname = $hehuoData['user_m_name'] ?: $hehuoData['user_username'];
                        $title = $redData['red_title'];
                        $image = $redData['red_image'];
                        $real_pay = $money - $redData['ru_money'];
                        $red_give = $redData['ru_money'];
                        //3、改一下当前红包的相关值
                        Db::name('m_red_user')
                            ->where('ru_id',$redData['ru_id'])
                            ->update([
                                'ru_user_id' => $user_id,
                                'ru_get_time' => date('Y-m-d H:i:s')
                            ]);
                        //4、用户实际应该付的款
                        $money = $money - $redData['ru_money'];
                        Db::name('record')->where('record_id',$record_id)
                            ->setField('record_ru_id',$redData['ru_id']);
                    }
                }
                $new_msg = ['uid' => $uid,'uname' => $uname,'title' => $title,'image' => $image,'real_pay' => $real_pay,'red_give' => $red_give];
                //-----------------------------算红包 end--------------------------------------
                if ($payment_type == 1) {
//                    $money = 0.01;
                    $ali = new Ali();
                    $res = $ali->getParam($order, $money, 'QRcodePay', '扫码支付', http_type() . '/api/Ali/huidiao1');
                } else if ($payment_type == 2) {
                    $wx = new Weixin();
//                    $money = 0.01;
                    $obj = [
                        'attach'       => "QRcodePay",
                        'body'         => "扫码支付",
                        'total_fee'    => $money * 100,
                        'out_trade_no' => $order,
                        'product_id'   => "",
                        'trade_type'   => "APP"
                    ];
                    $res = $wx->WeChatPayReady($obj, http_type() . '/api/Weixin/huidiao1');
                } else {
                    $openid = $this->getOpenId($miniCode);
                    if ($openid == '') {
                        return json(['status' => 100, 'msg' => '支付失败']);
                    }
                    $wx = new Wechat();
                    $obj = [
                        'attach'       => "QRcodePay",
                        'body'         => "扫码支付",
                        'total_fee'    => $money * 100,
                        'out_trade_no' => $order,
                        'product_id'   => "",
                        'trade_type'   => "JSAPI",
                        'openid'       => $openid
                    ];
                    $res = $wx->WeChatPayReady($obj, http_type() . '/api/Weixin/huidiao1');
                }
                Db::commit();
                return json(['status' => 220, 'msg' => $res,'new_msg' => $new_msg]);
            } else {
                $back = $this->consume($user_id, $integral, $shop_id);
                $rate = Db::name('jifen_conf')->where('conf_id', 2)->value('conf_rate');
                if ($back['status'] == 100) {
                    return json($back);
                } else {
                    Db::name('jifen_consume')->insert(['consume_content' => '扫码支付给“' . $shop['shop_name'] . '”' . $integral . '积分', 'consume_user_id' => $user_id, 'consume_add_time' => date("Y-m-d H:i:s")]);
                    Db::name('record')->where(['record_id' => $record_id])->update(['record_status' => 2, 'record_pay_time' => date("Y-m-d H:i:s"), 'record_shop_balance' => $shop['shop_balance'] + $integral * $rate, 'record_money' => $integral * $rate]);
                    Db::name('shop')->where('shop_id', $shop_id)->setInc('shop_balance', $integral * $rate);
                    Db::name('shop')->where('shop_id', $shop_id)->setInc('shop_all_balance', $integral * $rate);
                    shopjiluerror($shop_id,$integral * $rate,4);
                    try {
                        $yuan = round($integral * $rate, 2);
                        $this->sayMyName($shop_id,$yuan,0,$order,2);
                        $this->jpushShop(1, $shop_id, "收款{$integral}积分", ['type2' => 1024, 'msg' => "积分买单到账{$yuan}元"]);
                    } catch (\Exception $e) {
                        Log::record($e->getMessage(), 'error');
                    }
                    Db::commit();
                    return json(['status' => 200, 'msg' => '支付成功']);
                }
            }
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'msg' => "支付失败"]);
        }
    }


    public function collection()
    {
//        $this->redirect(url('admin/test/test'));
        extract(input());
        $id = str_replace(' ', '+', $id);
        $shop_id = $this->encrypt($id, 'DECODE');

        $user_id = Db::name('shop')->where('shop_id', $shop_id)->value('shop_user_id');
        $user_level = Db::name('u_user')->where('user_id', $user_id)->field('user_invite_code,user_level')->find();
        if ($user_level['user_level'] != 1) {
            $this->redirect(url('admin/share/indexnew') . '?code=' . $user_level['user_invite_code'] . '&shop_id=' . $shop_id);
        } else {
            $this->redirect(url('admin/share/indexnew') . '?code=&shop_id=' . $shop_id);
//            $this->redirect(url('admin/share/register') . '?code=&shop_id=' . $shop_id);
        }
    }

    public function getAccountInfo()
    {
        extract(input());
        $data = Db::name('u_user')
            ->where(['user_id' => $user_id])
            ->field('user_money_balance,user_money_balance_yet,user_balance,user_balance_yet,user_tx_account,user_tx_relname,user_tx_openid,user_tx_type')
            ->find();
        return json(['status' => 200, 'msg' => $data]);
    }

    public function getUserPrivacy()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        $data = Db::name('jifen_conf')->where(['conf_id' => 25])->find();
        return json(['status' => 200, 'msg' => $data]);
    }
    public function getShopPrivacy()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        $data = Db::name('jifen_conf')->where(['conf_id' => 48])->find();
        return json(['status' => 200, 'msg' => $data]);
    }

    public function frendInfo()
    {
        extract(input());
        $info1 = [];
        $info2 = [];
        if (!empty($he_id)) {
            $info1 = [];
            $he_id = explode(',', $he_id);
            $info1 = DB::name('u_user')->field('user_id,user_username,user_image,user_level,user_level2')
                ->where(['user_id' => ['in', $he_id]])
                ->select();
        }
        if (!empty($s_he_id)) {
            $info2 = [];
            $s_he_id = explode(',', $s_he_id);
            $info2 = DB::name('shop')->field('shop_id,shop_name,shop_img')
                ->where(['shop_id' => ['in', $s_he_id]])
                ->select();
        }
        $info['user_info'] = $info1;
        $info['shop_user_info'] = $info2;
        return json(['status' => 200, 'msg' => $info]);
    }

    // 未成为合伙人展示
    public function partnershow()
    {
        extract(input());
        $partner = array();
        $partners = DB::name('partner')->alias('par')
            ->join('u_user u', 'par.par_user_id = u.user_id')
            ->join('partner_class cl', 'par.par_class_id = cl.class_id')
            ->field('par.par_id,par.par_user_id,u.user_username,cl.class_name,par.par_add_time')
            ->where(['par_cancel' => 0])
            ->limit(20)
            ->order('par_add_time desc')
            ->select();
        $partner_class = DB::name('partner_class')
            ->field('class_id,class_level,class_name,class_money,class_info')
            ->select();
        $partner['partners'] = $partners;
        $partner['partner_class'] = $partner_class;
        return json(['status' => 200, 'msg' => $partner]);
    }

    // 付款成为合伙人
    public function partner_pay()
    {
        extract(input());
        $this->createInviteCodeInside($user_id);
        $class_money = DB::name('partner_class')->column('class_money');
        if (!in_array($money, $class_money)) {
            return json(['status' => 100, 'msg' => '支付金额错误']);
        }
        // 如果是升级合伙人
        if (!empty($up_type) && $up_type == 1) {

            $partner_class_level = DB::name('partner')
                ->where(['par_user_id' => $user_id, 'par_cancel' => 0])
                ->value('par_class_level');
            if ($partner_class_level >= $class_level) {
                return json(['status' => 100, 'msg' => '请升级更高级别合伙人！']);
            }
            //---不让这个情况的升级了（3行）---
            if($partner_class_level == 2 && $class_level == 3){
                return json(['status' => 100, 'msg' => '事业合伙人不可继续升级到城市合伙人！']);
            }
            // 升级合伙人只需要补付差额
            $old_money = DB::name('partner_class')
                ->where(['class_level' => $partner_class_level])
                ->value('class_money');
            $money = $money - $old_money;
            // 升级合伙人收益减掉之前的收益
            $old_class = DB::name('partner_class')
                ->where(['class_level' => $partner_class_level])
                ->find();
            $up_class = DB::name('partner_class')
                ->where(['class_level' => $class_level])
                ->find();
            $old_tui_jifen = $old_class['class_tui_jifen'] ? $old_class['class_tui_jifen'] : 0;
            $old_tui_money = $old_class['class_tui_money'] ? $old_class['class_tui_money'] : 0;
            $old_agent_money = $old_class['class_agent_money'] ? $old_class['class_agent_money'] : 0;
            $old_head_money = $old_class['class_head_money'] ? $old_class['class_head_money'] : 0;
            $up_tui_jifen = $up_class['class_tui_jifen'] ? $up_class['class_tui_jifen'] : 0;
            $up_tui_money = $up_class['class_tui_money'] ? $up_class['class_tui_money'] : 0;
            $up_agent_money = $up_class['class_agent_money'] ? $up_class['class_agent_money'] : 0;
            $up_head_money = $up_class['class_head_money'] ? $up_class['class_head_money'] : 0;
            if ($old_tui_jifen > $up_tui_jifen || $old_tui_money > $up_tui_money || $old_agent_money > $up_agent_money || $old_head_money > $up_head_money) {
                return json(['status' => 100, 'msg' => '配置有误，请联系管理员']);
            }

        }
        $is_partner = DB::name('partner')
            ->where(['par_user_id' => $user_id, 'par_cancel' => 0, 'par_class_level' => $class_level])
            ->find();
        if (!empty($is_partner)) {
            return json(['status' => 100, 'msg' => '您已是该合伙人']);
        }
        // 合伙人人数限制
        $place = DB::name('u_user')->where(['user_id' => $user_id])->value('user_area');
        if (empty($place)) {
            return json(['status' => 100, 'msg' => '请先完善定位资料']);
        } else {
            if (!empty($class_level) && $class_level == 3) {
                $where['par_class_level'] = $class_level;
                $where['par_cancel'] = 0;
                $where['par_qu_id'] = $place;
            } else {
                $where['par_class_level'] = $class_level;
                $where['par_cancel'] = 0;
            }
        }
        $level_count = DB::name('partner')
            ->where($where)
            ->count();
        $level_num = DB::name('partner_class')
            ->where(['class_level' => $class_level])
            ->field('class_id,class_num')
            ->find();
        if ($class_level != 1 && $level_count >= $level_num['class_num']) {
            return json(['status' => 100, 'msg' => '该合伙人名额已满！']);
        }
        Db::startTrans();
        try {
            $order = $this->getOrderNumber();
            $param = [
                'o_type'       => 11,
                'o_order_num'  => $order,
                'o_money'      => $money,
                'o_status'     => 5,
                'o_pay_type'   => $type,
                'o_pay_status' => 1,
                'o_user_id'    => $user_id,
                'o_class_id'   => $level_num['class_id'],
                'o_add_time'   => date('Y-m-d H:i:s'),
            ];
            if (!empty($up_type) && $up_type == 1) {
                $param['o_partner_up'] = $up_type;
            }
            Db::name('order')->insert($param);
            /*支付宝&微信支付操作*/
            if ($type == 1) {
                $ali = new Ali();
                $res = $ali->getParam($order, $money, 'upPartner', '升级合伙人');
            } else {
                $wx = new Weixin();
                $obj = [
                    'attach'       => "upPartner",
                    'body'         => "升级合伙人",//描述
                    'total_fee'    => $money * 100,//订单金额
                    'out_trade_no' => $order,//订单号
                    'product_id'   => "",//产品ID
                    'trade_type'   => "APP"//类型
                ];
                $res = $wx->WeChatPayReady($obj);
            }
            Db::commit();
            return json(['status' => 200, 'class_level' => $class_level, 'msg' => $res]);
        } catch (\Exception $e) {
            Db::rollback();
            Log::record($e->getMessage(), 'error');
            return json(['status' => 100, 'class_level' => $class_level, 'msg' => "支付失败"]);
        }
    }

    // 以前的合伙人可以修改一次加入时间
    public function edittime()
    {
        extract(input());
        $par_add_time = DB::name('partner')
            ->where(['par_user_id' => $user_id, 'par_status' => 2, 'par_cancel' => 0])
            ->value('par_add_time');
        if (!empty($par_add_time)) {
            if ($par_add_time > '2020-03-18 00:00:00') {
                return json(['status' => 100, 'msg' => '您不需要/已修改过加入时间']);
            }
            $now_add_time = date('Y-m-d H:i:s', time());
            $res = DB::name('partner')
                ->where(['par_user_id' => $user_id, 'par_status' => 2, 'par_cancel' => 0])
                ->update(['par_add_time' => $now_add_time, 'par_add_oldtime' => $par_add_time]);
            if (!empty($res)) {
                return json(['status' => 200, 'msg' => '修改成功']);
            } else {
                return json(['status' => 100, 'msg' => '修改失败']);
            }
        } else {
            $now_add_time = date('Y-m-d H:i:s', time());
            $res = DB::name('partner')
                ->where(['par_user_id' => $user_id, 'par_status' => 2, 'par_cancel' => 0])
                ->update(['par_add_time' => $now_add_time]);
            if (!empty($res)) {
                return json(['status' => 200, 'msg' => '修改成功']);
            } else {
                return json(['status' => 100, 'msg' => '修改失败']);
            }
        }
    }

    // 合伙人页展示
    public function myPartnerShow()
    {
        extract(input());
        $partner = array();
        // 合伙人姓名
        $par = DB::name('partner')
            ->where(['par_id' => $par_id])
            ->find();
        $partner['par'] = DB::name('partner_class')
            ->where(['class_id' => $par['par_class_id']])
            ->value('class_name');
        $partner['par_class_level'] = $par['par_class_level'];
        $partner['par_id'] = $par['par_id'];
        // 合伙人邀请粉丝积分收益
        $par_fans_integral = DB::name('u_user')
            ->where(['user_id' => $user_id])
            ->value('user_fans_integral');
        $partner['par_fans_integral'] = $par_fans_integral;
        // 店铺提成收益
        $user_par = DB::name('u_user')
            ->where(['user_id' => $user_id])
            ->field('user_id,user_par_integral,user_par_money,user_shop_money,user_money_balance,user_money_balance_yet')
            ->find();
        $par_shop_amount = $user_par['user_shop_money'];
        $partner['par_shop_amount'] = $par_shop_amount ? $par_shop_amount : 0;
        // 合伙人邀请收益
        $partner['user_par_integral'] = $user_par['user_par_integral'] ? $user_par['user_par_integral'] : 0;
        $partner['user_par_money'] = $user_par['user_par_money'] ? $user_par['user_par_money'] : 0;
        // 总积分收益
        $partner['all_integral'] = $par_fans_integral + $partner['user_par_integral'];
        // 总现金收益可提现
        $partner['all_money'] = $user_par['user_money_balance'];
        // 可升级的合伙人类型
        $partner_class = DB::name('partner_class')
            ->where('class_level', '>', $par['par_class_level'])
            ->field('class_id,class_level,class_name,class_money,class_info')
            ->select();
        $partner['partner_class'] = $partner_class;
        if (!empty($par_id) && !empty($user_id)) {
            return json(['status' => 200, 'msg' => $partner]);
        } else {
            return json(['status' => 100, 'msg' => "缺少参数！"]);
        }
    }

    // 合伙人粉丝邀请详情展示
    public function fansDetail()
    {
        extract(input());
        $par_invite_fans = array();
        $user_fans = DB::name('u_user')
            ->where(['user_recommend' => $user_id])
            ->field('user_id,user_username,user_phone,user_shop_id,user_level,user_time,user_level2,user_edit_image,user_edit_username,user_image')
            ->order('user_time desc')
            ->page($page1, 10)
            ->select();
        $user_fans1s = DB::name('u_user')
            ->where(['user_recommend' => $user_id])
            ->order('user_time desc')
            ->select();
        // 提醒完善资料获得积分
        $edit_jifen = DB::name('partner_class')
            ->where(['class_level' => $class_level])
            ->field('class_fans_jifen_edi,class_fans_days')
            ->find();
        // 昨天
        $yesterday = date("Y-m-d", strtotime("-1 day"));
        // 合伙人信息
        $par_add_time = DB::name('partner')
            ->where(['par_id' => $par_id])
            ->value('par_add_time');
        $par_invite_fans['fans_days'] = $edit_jifen['class_fans_days'];
        $par_invite_fans['par_add_time'] = $par_add_time;
        $par_fans1 = [];
        $par_fans2 = [];
        $par_fans3 = [];
        $par_invite_fans['count'] = 0;
        if (!empty($user_fans)) {
            foreach ($user_fans as $key => $vo) {
                if ($vo['user_level2'] == 2) {
                    $user_fans[$key]['user_level_name'] = '店主';
                } elseif ($vo['user_level'] == 1) {
                    $user_fans[$key]['user_level_name'] = '普通用户';
                }
                if ($vo['user_level'] == 2) {
                    $user_fans[$key]['user_level_name'] = '城市合伙人';
                } elseif ($vo['user_level'] == 3) {
                    $user_fans[$key]['user_level_name'] = '事业合伙人';
                } elseif ($vo['user_level'] == 4) {
                    $user_fans[$key]['user_level_name'] = '推广合伙人';
                }
                $user_fans[$key]['edit_jifen'] = $edit_jifen['class_fans_jifen_edi'];
                $date = substr($vo['user_time'], 0, 10);
                $par_fans1[$date][] = $user_fans[$key];
            }
            // $par_invite_fans['one_fans'] = $par_fans1;
            // 一级人数
            $par_invite_fans['count'] = count($user_fans1s);
            // 昨日一级粉丝新增
            if (!empty($par_fans1[$yesterday])) {
                $par_invite_fans['yesterday_count'] = count($par_fans1[$yesterday]);
            } else {
                $par_invite_fans['yesterday_count'] = 0;
            }
            $user_ids2 = array_column($user_fans1s, 'user_id');
            if ($class_level == 2 || $class_level == 3) {
                // 二级粉丝
                $user_fans2 = DB::name('u_user')
                    ->where(['user_recommend' => ['in', $user_ids2]])
                    ->field('user_id,user_username,user_phone,user_shop_id,user_level,user_time,user_level2,user_edit_image,user_edit_username,user_image')
                    ->order('user_time desc')
                    ->page($page2, 10)
                    ->select();
                $user_fans2s = DB::name('u_user')
                    ->where(['user_recommend' => ['in', $user_ids2]])
                    ->order('user_time desc')
                    ->select();
                if (!empty($user_fans2)) {
                    // $par_fans2 = [];
                    foreach ($user_fans2 as $key => $vo) {
                        if ($vo['user_level2'] == 2) {
                            $user_fans2[$key]['user_level_name'] = '店主';
                        } elseif ($vo['user_level'] == 1) {
                            $user_fans2[$key]['user_level_name'] = '普通用户';
                        }
                        if ($vo['user_level'] == 2) {
                            $user_fans2[$key]['user_level_name'] = '城市合伙人';
                        } elseif ($vo['user_level'] == 3) {
                            $user_fans2[$key]['user_level_name'] = '事业合伙人';
                        } elseif ($vo['user_level'] == 4) {
                            $user_fans2[$key]['user_level_name'] = '推广合伙人';
                        }
                        $user_fans2[$key]['edit_jifen'] = $edit_jifen['class_fans_jifen_edi'];
                        $date2 = substr($vo['user_time'], 0, 10);
                        $par_fans2[$date2][] = $user_fans2[$key];
                    }

                    // $par_invite_fans['two_fans'] = $par_fans2;
                    // 二级人数
                    $par_invite_fans['count'] = count($user_fans1s) + count($user_fans2s);
                    // 昨日二级粉丝新增
                    if (!empty($par_fans2[$yesterday])) {
                        $par_invite_fans['yesterday_count'] = $par_invite_fans['yesterday_count'] + count($par_fans2[$yesterday]);
                    } else {
                        $par_invite_fans['yesterday_count'] = $par_invite_fans['yesterday_count'];
                    }
                    $user_ids3 = array_column($user_fans2s, 'user_id');
                    if ($class_level == 3) {
                        // 三级粉丝
                        $user_fans3 = DB::name('u_user')
                            ->where(['user_recommend' => ['in', $user_ids3]])
                            ->field('user_id,user_username,user_phone,user_shop_id,user_level,user_time,user_level2,user_edit_image,user_edit_username,user_image')
                            ->order('user_time desc')
                            ->page($page3, 10)
                            ->select();
                        $user_fans3s = DB::name('u_user')
                            ->where(['user_recommend' => ['in', $user_ids3]])
                            ->order('user_time desc')
                            ->select();
                        if (!empty($user_fans3)) {
                            // $par_fans3 = [];
                            foreach ($user_fans3 as $key => $vo) {
                                if ($vo['user_level2'] == 2) {
                                    $user_fans3[$key]['user_level_name'] = '店主';
                                } elseif ($vo['user_level'] == 1) {
                                    $user_fans3[$key]['user_level_name'] = '普通用户';
                                }
                                if ($vo['user_level'] == 2) {
                                    $user_fans3[$key]['user_level_name'] = '城市合伙人';
                                } elseif ($vo['user_level'] == 3) {
                                    $user_fans3[$key]['user_level_name'] = '事业合伙人';
                                } elseif ($vo['user_level'] == 4) {
                                    $user_fans3[$key]['user_level_name'] = '推广合伙人';
                                }
                                $user_fans3[$key]['edit_jifen'] = $edit_jifen['class_fans_jifen_edi'];
                                $date3 = substr($vo['user_time'], 0, 10);
                                $par_fans3[$date3][] = $user_fans3[$key];
                            }
                            // $par_invite_fans['three_fans'] = $par_fans3;
                            // 三级人数
                            $par_invite_fans['count'] = count($user_fans1s) + count($user_fans2s) + count($user_fans3s);
                            if (!empty($par_fans3[$yesterday])) {
                                $par_invite_fans['yesterday_count'] = $par_invite_fans['yesterday_count'] + count($par_fans3[$yesterday]);
                            } else {
                                $par_invite_fans['yesterday_count'] = $par_invite_fans['yesterday_count'];
                            }
                        }
                    }
                }
            }
        }
        krsort($par_fans1);
        krsort($par_fans2);
        krsort($par_fans3);
        $par_invite_fans['one_fans'] = $par_fans1;
        $par_invite_fans['two_fans'] = $par_fans2;
        $par_invite_fans['three_fans'] = $par_fans3;
        $par_invite_fans['count'] = $par_invite_fans['count'];
        if (!empty($user_id) && !empty($class_level) && !empty($par_id)) {
            return json(['status' => 200, 'msg' => $par_invite_fans]);
        } else {
            return json(['status' => 100, 'msg' => '缺少参数！']);
        }
    }

    // 店铺收益详情
    public function inviteShop()
    {
        extract(input());
        $par_invite_shop = array();
        $user_ids = DB::name('u_user')
            ->where(['user_recommend' => $user_id])
            ->column('user_id');
        $fans_shop = DB::name('u_user')->alias('u')
            ->join('shop sh', 'u.user_shop_id = sh.shop_id')
            ->where(['user_recommend' => $user_id])
            ->field('u.user_id,u.user_username,sh.shop_id,sh.shop_time,sh.shop_img,sh.shop_name,sh.shop_today_balance')
            ->order('sh.shop_time desc')
            ->page($page1, 10)
            ->select();
        $fans_shop1s = DB::name('u_user')->alias('u')
            ->join('shop sh', 'u.user_shop_id = sh.shop_id')
            ->where(['user_recommend' => $user_id])
            ->order('sh.shop_time desc')
            ->select();
        // 昨天
        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $par_fans_shop1 = [];
        $par_fans_shop2 = [];
        $par_fans_shop3 = [];
        $par_invite_shop['count'] = 0;
        if (!empty($user_ids)) {
            // $par_fans_shop1 = [];
            foreach ($fans_shop as $key => $vo) {
                // 我的收益
                $user_conf = DB::name('partner_class')
                    ->where(['class_level' => $class_level])
                    ->value('class_only_rate');
                $lesssy = Db::name('record')
                    ->where('record_shop_id',$vo['shop_id'])
                    ->whereTime('record_pay_time','d')
                    ->where('record_type',1)
                    ->where('record_status',2)
                    ->where('record_give_jifen',0)
                    ->sum('record_money');
                $lesssy2 = Db::name('record')
                    ->where('record_shop_id',$vo['shop_id'])
                    ->whereTime('record_pay_time','d')
                    ->where('record_type','in','1,3')
                    ->where('record_status',2)
                    ->where('record_give_jifen','>',0)
                    ->where('record_zhekou',2)
                    ->sum('record_money');
                $fans_shop[$key]['user_conf_money'] = round(($vo['shop_today_balance']-$lesssy-$lesssy2) * $user_conf / 1000,3);
                if($fans_shop[$key]['user_conf_money'] < 0) $fans_shop[$key]['user_conf_money'] = 0;
                $date = substr($vo['shop_time'], 0, 10);
                $par_fans_shop1[$date][] = $fans_shop[$key];
            }
            // $par_invite_shop['one_fans_shop'] = $par_fans_shop1;
            // 一级粉丝开店人数
            $par_invite_shop['count'] = count($fans_shop1s);
            // 昨日一级粉丝开店新增
            if (!empty($par_fans_shop1[$yesterday])) {
                $par_invite_shop['yesterday_count'] = count($par_fans_shop1[$yesterday]);
            } else {
                $par_invite_shop['yesterday_count'] = 0;
            }
            if ($class_level == 2 || $class_level == 3) {
                // 二级粉丝开店人数
                $user_ids2 = DB::name('u_user')
                    ->where(['user_recommend' => ['in', $user_ids]])
                    ->column('user_id');
                $fans_shop2 = DB::name('u_user')->alias('u')
                    ->join('shop sh', 'u.user_shop_id = sh.shop_id')
                    ->where(['user_recommend' => ['in', $user_ids]])
                    ->field('u.user_id,u.user_username,sh.shop_id,sh.shop_time,sh.shop_img,sh.shop_name,sh.shop_today_balance')
                    ->order('sh.shop_time desc')
                    ->page($page2, 10)
                    ->select();
                $fans_shop2s = DB::name('u_user')->alias('u')
                    ->join('shop sh', 'u.user_shop_id = sh.shop_id')
                    ->where(['user_recommend' => ['in', $user_ids]])
                    ->order('sh.shop_time desc')
                    ->select();
                if (!empty($user_ids2)) {
                    // $par_fans_shop2 = [];
                    foreach ($fans_shop2 as $key => $vo) {
                        // 我的收益
                        $user_conf = DB::name('partner_class')
                            ->where(['class_level' => $class_level])
                            ->value('class_only_rate');
                        $fans_shop2[$key]['user_conf_money'] = $vo['shop_today_balance'] * $user_conf / 1000;
                        $date2 = substr($vo['shop_time'], 0, 10);
                        $par_fans_shop2[$date2][] = $fans_shop2[$key];
                    }
                    $par_invite_shop['two_fans_shop'] = $par_fans_shop2;
                    // 二级人数
                    $par_invite_shop['count'] = count($fans_shop1s) + count($fans_shop2s);
                    // 昨日二级粉丝新增
                    if (!empty($par_fans_shop2[$yesterday])) {
                        $par_invite_shop['yesterday_count'] = $par_invite_shop['yesterday_count'] + count($par_fans_shop2[$yesterday]);
                    } else {
                        $par_invite_shop['yesterday_count'] = $par_invite_shop['yesterday_count'];
                    }
                    // $user_ids2 = $user_ids2;
                    if ($class_level == 3) {
                        // 三级粉丝
                        $fans_shop3 = DB::name('u_user')->alias('u')
                            ->join('shop sh', 'u.user_shop_id = sh.shop_id')
                            ->where(['user_recommend' => ['in', $user_ids2]])
                            ->field('u.user_id,u.user_username,sh.shop_id,sh.shop_time,sh.shop_img,sh.shop_name,sh.shop_today_balance')
                            ->order('sh.shop_time desc')
                            ->page($page3, 10)
                            ->select();
                        $fans_shop3s = DB::name('u_user')->alias('u')
                            ->join('shop sh', 'u.user_shop_id = sh.shop_id')
                            ->where(['user_recommend' => ['in', $user_ids2]])
                            ->order('sh.shop_time desc')
                            ->select();
                        if (!empty($fans_shop3)) {
                            // $par_fans_shop3 = [];
                            foreach ($fans_shop3 as $key => $vo) {
                                // // 我的收益
                                $user_conf = DB::name('partner_class')
                                    ->where(['class_level' => $class_level])
                                    ->value('class_only_rate');
                                $fans_shop3[$key]['user_conf_money'] = $vo['shop_today_balance'] * $user_conf / 1000;
                                $date3 = substr($vo['shop_time'], 0, 10);
                                $par_fans_shop3[$date3][] = $fans_shop3[$key];
                            }
                            $par_invite_shop['three_fans_shop'] = $par_fans_shop3;
                            // 三级人数
                            $par_invite_shop['count'] = count($fans_shop1s) + count($fans_shop2s) + count($fans_shop3s);
                            if (!empty($par_fans_shop3[$yesterday])) {
                                $par_invite_shop['yesterday_count'] = $par_invite_shop['yesterday_count'] + count($par_fans_shop3[$yesterday]);
                            } else {
                                $par_invite_shop['yesterday_count'] = $par_invite_shop['yesterday_count'];
                            }
                        }
                    }
                }
            }
        }
        $par_invite_shop['one_fans_shop'] = $par_fans_shop1;
        $par_invite_shop['two_fans_shop'] = $par_fans_shop2;
        $par_invite_shop['three_fans_shop'] = $par_fans_shop3;
        $par_invite_shop['count'] = $par_invite_shop['count'];
        if (!empty($user_id) && !empty($class_level)) {
            return json(['status' => 200, 'msg' => $par_invite_shop]);
        } else {
            return json(['status' => 100, 'msg' => '缺少参数！']);
        }
    }

    // 合伙人邀请详情
    public function invitePartner()
    {
        extract(input());
        $partner1 = array();
        $partner2 = array();
        $partner3 = array();
        $partners = array();
        // 推广合伙人
        $par1 = DB::name('partner')->alias('par')
            ->join('u_user u', 'par.par_user_id = u.user_id')
            ->join('partner_class cl', 'par.par_class_id = cl.class_id')
            ->where(['par_parent_id' => $par_id, 'par_class_level' => 1, 'par_cancel' => 0, 'par_status' => 2])
            ->field('par.*,u.user_id,u.user_image,u.user_username,cl.class_name,cl.class_tui_jifen,cl.class_tui_money')
            ->order('par.par_add_time desc')
            ->page($page1, 10)
            ->select();
        // 事业合伙人
        $par2 = DB::name('partner')->alias('par')
            ->join('u_user u', 'par.par_user_id = u.user_id')
            ->join('partner_class cl', 'par.par_class_id = cl.class_id')
            ->where(['par_parent_id' => $par_id, 'par_class_level' => 2, 'par_cancel' => 0, 'par_status' => 2])
            ->field('par.*,u.user_id,u.user_image,u.user_username,cl.class_name,cl.class_tui_jifen,cl.class_tui_money')
            ->order('par.par_add_time desc')
            ->page($page2, 10)
            ->select();
        // 城市合伙人
        $par3 = DB::name('partner')->alias('par')
            ->join('u_user u', 'par.par_user_id = u.user_id')
            ->join('partner_class cl', 'par.par_class_id = cl.class_id')
            ->where(['par_parent_id' => $par_id, 'par_class_level' => 3, 'par_cancel' => 0, 'par_status' => 2])
            ->field('par.*,u.user_id,u.user_image,u.user_username,cl.class_name,cl.class_tui_jifen,cl.class_tui_money')
            ->order('par.par_add_time desc')
            ->page($page3, 10)
            ->select();
        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $partners['count'] = DB::name('partner')
            ->where(['par_parent_id' => $par_id, 'par_cancel' => 0])
            ->count();
        $partners['yesterday_count'] = DB::name('partner')->alias('par')
            ->where(['par_parent_id' => $par_id, 'par_cancel' => 0])
            ->whereTime('par_add_time', 'yesterday')
            ->count();
        // 按日期分类
        foreach ($par1 as $k1 => $v1) {
            $date = substr($v1['par_add_time'], 0, 10);
            $partner1[$date][] = $v1;
        }
        // 按日期分类
        foreach ($par2 as $k2 => $v2) {
            $date = substr($v2['par_add_time'], 0, 10);
            $partner2[$date][] = $v2;
        }
        // 按日期分类
        foreach ($par3 as $k3 => $v3) {
            $date = substr($v3['par_add_time'], 0, 10);
            $partner3[$date][] = $v3;
        }
        $partners['tui'] = $partner1;
        $partners['shi'] = $partner2;
        $partners['city'] = $partner3;
        if (!empty($user_id) && !empty($par_id)) {
            return json(['status' => 200, 'msg' => $partners]);
        } else {
            return json(['status' => 100, 'msg' => '缺少参数！']);
        }
    }

    /**
     * 事业合伙人积分流通收益
     */
    public function partnerIncome()
    {
        extract(input());
        $place = Db::name('u_user')->where('user_id', $user_id)->value('user_area');
        $area = Db::name('area')->where('district_id', $place)->value('district');
        $member_count = Db::name('u_user')->count();//会员总数
        $new_count = Db::name('u_user')->whereTime('user_time', 'today')->count();//新增会员总数
        $user = Db::name('u_user')->where('user_id', $user_id)->find();//用户
        // 总事业合伙人数
        $partners = DB::name('partner')->where(['par_class_level' => 2, 'par_status' => 2, 'par_cancel' => 0])->count();
        // 今日新增事业合伙人
        $par_today = DB::name('partner')->where(['par_class_level' => 2, 'par_status' => 2, 'par_cancel' => 0])->whereTime('par_add_time', 'today')->count();
        // 前20订单的合伙人实时积分收益
        $list = Db::query("SELECT * FROM((SELECT o_id,user_id,user_image,user_phone,user_username,o_jifen,shop_name,district,o_add_time FROM up_order o INNER JOIN up_u_user u ON u.user_id = o.o_user_id INNER JOIN up_shop s ON s.shop_id = o.o_shop_id INNER JOIN up_area a ON a.district_id = s.shop_qu_id WHERE o_type = 1 AND o_pay_status = 2) UNION ALL (SELECT '0' as o_id,user_id,user_image,user_phone,user_username,record_jifen as o_jifen,shop_name,district,record_add_time as o_add_time FROM up_record as r INNER JOIN up_u_user u ON u.user_id = r.record_user_id INNER JOIN up_shop s ON s.shop_id = r.record_shop_id INNER JOIN up_area a ON a.district_id = s.shop_qu_id WHERE record_type = 2 AND record_status = 2)) as l ORDER By l.o_add_time DESC limit 20");
        if (!empty($list)) {
            // 事业合伙人分红比例
            $rate = Db::name('jifen_conf')->where(['conf_id' => 28])->value('conf_rate');
            foreach ($list as $key => $vo) {
                $list[$key]['partner'] = round($vo['o_jifen'] * $rate, 2);
                if ($vo['user_username'] == $vo['user_phone']) {
                    $list[$key]['user_username'] = substr($vo['user_username'], 0, 4) . '****' . substr($vo['user_username'], 8, 3);
                }
            }
        }
        $ling = Db::name('token')->where('id',3)->find ();
        $data = [
            'jifen_list'     => $list,
            'partners'       => $partners,
            'par_today'      => $par_today,
            'area'           => $area,
            'member'         => $member_count + 10000 + $ling['time'],//会员总数
            'new'            => $new_count + $ling['token'],//新增会员总数
            'today_jifen'    => $user['user_today_jifen'],//今天交易额
            'today_income'   => round($user['user_today_income'], 2),//今天总收益
            'partner_income' => round($user['user_partner_income'], 2),//事业合伙人总收益
            'my_income'      => round($user['user_my_income'], 2),//我的今日收益
            'balance'        => $user['user_balance'],
            'balance_yet'    => $user['user_balance_yet']
        ];
        if (!empty($user_id)) {
            return json(['status' => 200, 'msg' => $data]);
        } else {
            return json(['status' => 100, 'msg' => '缺少参数！']);
        }
    }

    // 邀请页面
    public function par_invite()
    {
        $partners = DB::name('partner')->alias('par')
            ->join('u_user u', 'par.par_user_id = u.user_id')
            ->join('partner_class cl', 'par.par_class_id = cl.class_id')
            ->field('par.par_id,par.par_user_id,u.user_username,cl.class_name,par.par_add_time')
            ->where(['par_cancel' => 0])
            ->limit(20)
            ->order('par_add_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $partners]);
    }

    // 定位
    public function location()
    {
        extract(input());
        // 合伙人人数限制
        $place = DB::name('u_user')->where(['user_id' => $user_id])->value('user_area');
        if (empty($place)) {
            $area = false;
        } else {
            $area = true;
        }
        return json(['status' => 200, 'msg' => $area]);
    }

    // 合伙人邀请粉丝已读未读
    public function fansread()
    {
        extract(input());
        if (!empty($level)) {
            DB::name('partner_read')
                ->where(['read_user_id' => $user_id, 'read_level' => $level, 'read_level_user_id' => ['<>', '']])
                ->update(['read_status' => 1, 'read_time' => date('Y-m-d H:i:s', time())]);
        }
        $count1 = DB::name('partner_read')
            ->where(['read_user_id' => $user_id, 'read_level' => 1, 'read_status' => 0, 'read_level_user_id' => ['<>', '']])
            ->count();
        $count2 = DB::name('partner_read')
            ->where(['read_user_id' => $user_id, 'read_level' => 2, 'read_status' => 0, 'read_level_user_id' => ['<>', '']])
            ->count();
        $count3 = DB::name('partner_read')
            ->where(['read_user_id' => $user_id, 'read_level' => 3, 'read_status' => 0, 'read_level_user_id' => ['<>', '']])
            ->count();
        $count['one_count'] = $count1;
        $count['two_count'] = $count2;
        $count['three_count'] = $count3;
        return json(['status' => 200, 'msg' => $count]);
    }

    // 同城购物轮播图,城主推荐,本地畅销,本地服务,今日上新,总部推荐,为你推荐
    public function citybuy()
    {
        extract(input());
        $admin = DB::name('admin')->where(['area' => $qu])->find();
        if (!empty($admin)) {
            $where['b_type'] = 3;
            $where['b_area_id'] = $qu;
        } else {
            $where['b_type'] = 1;
        }
        // 轮播图
        $banner = DB::name('banner')
            ->where($where)
            ->limit(5)
            ->select();
        // 城主推荐
        $admin_tj = Db::name('product p')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where(['p_type' => 1, 'p_status' => 4, 'p_admin_tj' => 2, 'shop_qu_id' => $qu])
            ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give,p_postage,shop_name')
            ->order('p_sort desc')
            ->limit(4)
            ->select();
        if (empty($admin_tj)) {
            $admin_tj = Db::name('product p')
                ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
                ->where(['p_type' => 1, 'p_status' => 4, 'p_admin_tj_zong' => 2])
                ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give,p_postage,shop_name')
                ->order('p_sort desc')
                ->limit(4)
                ->select();
        }
        if (!empty($admin_tj)) {
            foreach ($admin_tj as $key => $vo) {
                if ($vo['p_model'] == 2) {
                    $admin_tj[$key]['model'] = DB::name('product_model')
                        ->where(['m_product_id' => $vo['p_id']])
                        ->select();
                } else {
                    $admin_tj[$key]['model'] = '';
                }
                $admin_tj[$key]['buy_num'] = 1;
            }
        }
        // 本地畅销
        $p_sale = Db::name('product p')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where(['p_type' => 1, 'p_status' => 4, 'shop_qu_id' => $qu])
            ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_postage,p_give,shop_name')
            ->order('p_sell_yet desc,p_sort desc')
            ->limit(10)
            ->select();
        if (!empty($p_sale)) {
            foreach ($p_sale as $key => $vo) {
                if ($vo['p_model'] == 2) {
                    $p_sale[$key]['model'] = DB::name('product_model')
                        ->where(['m_product_id' => $vo['p_id']])
                        ->select();
                } else {
                    $p_sale[$key]['model'] = '';
                }
                $p_sale[$key]['buy_num'] = 1;
            }
        }
        // 本地服务
        $p_native = Db::name('shop')
            ->where(['shop_attestation' => 2, 'shop_status' => 1, 'shop_qu_id' => $qu, 'shop_native' => 1])
            ->field('shop_id,shop_range,shop_name,shop_img,shop_browse,shop_banner,shop_link,shop_introduce,shop_time,shop_qu_id,shop_lon,shop_lat,shop_address,shop_contact,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((' . $lat . '* PI() / 180 - shop_lat * PI() / 180) / 2),2) + COS(' . $lat . ' * PI() / 180) * COS(shop_lat * PI() / 180) * POW(SIN((' . $lon . ' * PI() / 180 - shop_lon * PI() / 180) / 2),2))),2) AS distance')
            ->order('shop_time')
            ->limit(4)
            ->select();
        if (!empty($p_native)) {
            foreach ($p_native as $key => $vo) {
                $product_ids = DB::name('product')->where('p_shop_id', $vo['shop_id'])->column('p_id');
                $shop_product = DB::name('product')
                    ->where(['p_type' => 1, 'p_status' => 4])
                    ->where('p_shop_id', $vo['shop_id'])
                    ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give')
                    ->order('p_add_time desc')
                    ->limit(10)
                    ->select();
                if (!empty($product_ids)) {
                    $star = DB::name('appraise')->where(['app_p_id' => ['in', $product_ids]])->avg('app_type');
                    if (!empty($star)) {
                        $star = ceil($star);
                        // 店铺星级，所有商品评价平均值
                        $p_native[$key]['p_star'] = $star;
                    } else {
                        // 没有商品给5星
                        $p_native[$key]['p_star'] = 5;
                    }
                } else {
                    // 没有商品给5星
                    $p_native[$key]['p_star'] = 5;
                }
                // 店铺商品
                $p_native[$key]['shop_product'] = $shop_product;
            }
        }
        // 每日上新
        $p_today = Db::name('product p')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where(['p_type' => 1, 'p_status' => 4, 'shop_qu_id' => $qu])
//            ->where(['p_type'=>1,'p_status'=>4])
            ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give,p_postage,shop_name')
            ->order('p_add_time desc')
            ->limit(4)
            ->select();
        if (!empty($p_today)) {
            foreach ($p_today as $key => $vo) {
                if ($vo['p_model'] == 2) {
                    $p_today[$key]['model'] = DB::name('product_model')
                        ->where(['m_product_id' => $vo['p_id']])
                        ->select();
                } else {
                    $p_today[$key]['model'] = '';
                }
                $p_today[$key]['buy_num'] = 1;
            }
        }
        // 总部推荐
        $p_head_tj = Db::name('product p')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where(['p_type' => 1, 'p_status' => 4, 'p_head_tj' => 2])
            ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give,p_postage,shop_name')
            ->order('p_sort desc')
            ->select();
        if (!empty($p_head_tj)) {
            foreach ($p_head_tj as $key => $vo) {
                if ($vo['p_model'] == 2) {
                    $p_head_tj[$key]['model'] = DB::name('product_model')
                        ->where(['m_product_id' => $vo['p_id']])
                        ->select();
                } else {
                    $p_head_tj[$key]['model'] = '';
                }
                $p_head_tj[$key]['buy_num'] = 1;
            }
        }
        // 为你推荐
        $p_you_tj = Db::name('product p')
            ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
            ->where(['p_type' => 1, 'p_status' => 4, 'p_you_tj' => 2])
            ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give,p_postage,shop_name')
            ->order('p_sort desc')
            ->select();
        if (!empty($p_you_tj)) {
            foreach ($p_you_tj as $key => $vo) {
                if ($vo['p_model'] == 2) {
                    $p_you_tj[$key]['model'] = DB::name('product_model')
                        ->where(['m_product_id' => $vo['p_id']])
                        ->select();
                } else {
                    $p_you_tj[$key]['model'] = '';
                }
                $p_you_tj[$key]['buy_num'] = 1;
            }
        }
        $data['banner'] = $banner;
        $data['admin_tj'] = $admin_tj;
        $data['p_sale'] = $p_sale;
        $data['p_native'] = $p_native;
        $data['p_today'] = $p_today;
        $data['p_head_tj'] = $p_head_tj;
        $data['p_you_tj'] = $p_you_tj;
        return json(['status' => 200, 'msg' => $data]);
    }

    /**
     * 同城购物,城主推荐,本地畅销,今日上新,总部推荐,为你推荐更多数据
     * @return \think\response\Json
     */
    public function cityMore()
    {
        extract(input());
        $where = [
            'p_status' => 4,
        ];
        if (!empty($cate)) {
            $where['p_cate'] = $cate;
        }
        $c_id = '';
        switch ($type) {
            case 1:
                $where['p_admin_tj'] = 2;//城主推荐
                $where['shop_qu_id'] = $qu;//城主推荐
                $where['p_type'] = 1;//同城购物
                $c_id = 33;
                break;
            case 2:
                $where['shop_qu_id'] = $qu;//本地畅销
                $xu = 'p_sell_yet desc';
                $where['p_type'] = 1;//同城购物
                $c_id = 34;
                break;
            case 3:
                $xu = 'p_add_time desc';// 每日上新
                $where['p_type'] = 1;//同城购物
                $where['shop_qu_id'] = $qu;
                $c_id = 36;
                break;
            case 4:
                $where['p_head_tj'] = 2;//总部推荐
                $where['p_type'] = 1;//同城购物
                $c_id = 38;
                break;
            case 5:
                $where['p_type'] = 1;//同城购物
                $where['p_you_tj'] = 2;//为你推荐
                $c_id = 37;
                break;
            case 6:
                $where['p_type'] = ['in', '2,3'];//积分商品
                $where['p_today_th'] = 2;//今日特惠
                $c_id = 42;
                break;
            case 7:
                $where['p_type'] = ['in', '2,3'];//积分商品
                $where['p_city_th'] = 2;//同城特惠
                if (isset($qu) && $qu) {
                    $where['shop_qu_id'] = $qu;
                }
                $c_id = 43;
                break;
            case 8:
                $where['p_type'] = ['in', '2,3'];//积分商品
                $where['p_man_tj'] = 2;//人气推荐
                if (isset($qu) && $qu) {
                    $where['shop_qu_id'] = $qu;
                }
                $c_id = 41;
                break;
        }
        switch ($sort) {
            case 1:
                $xu = 'p_now_price asc'; //价格倒序
                break;
            case 2:
                $xu = 'p_now_price desc';  //价格正序
                break;
            case 3:
                $xu = 'p_sell_yet desc';//综合排序
                break;
            case 4:
                $xu = 'p_add_time desc'; // 上架时间
                break;
            default:
                $xu = 'p_sort desc';//审核时间
        }
        if ($type == 1 || $type == 2) {
            $data = Db::name('product p')
                ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
                ->where($where)
                ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give,p_postage,shop_name')
                ->order($xu)
                ->page($page, 10)
                ->select();
            if (empty($data) && $type == 1 && $page == 1) {
                $data = Db::name('product p')
                    ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
                    ->where(['p_type' => 1, 'p_status' => 4, 'p_admin_tj_zong' => 2])
                    ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give,p_postage,shop_name')
                    ->order($xu)
                    ->page($page, 10)
                    ->select();
            }
            if (!empty($data)) {
                foreach ($data as $key => $vo) {
                    if ($vo['p_model'] == 2) {
                        $data[$key]['model'] = DB::name('product_model')
                            ->where(['m_product_id' => $vo['p_id']])
                            ->select();
                    } else {
                        $data[$key]['model'] = '';
                    }
                    $data[$key]['buy_num'] = 1;
                }
            }
        } else {
            $data = Db::name('product p')
                ->join('shop s', 'p.p_shop_id = s.shop_id', 'left')
                ->field('p.*,shop_name')
                ->where($where)
                ->page($page, 10)
                ->order($xu)
                ->select();
            if (!empty($data)) {
                foreach ($data as $key => $vo) {
                    if ($vo['p_model'] == 2) {
                        $data[$key]['model'] = DB::name('product_model')
                            ->where(['m_product_id' => $vo['p_id']])
                            ->select();
                    } else {
                        $data[$key]['model'] = '';
                    }
                    $data[$key]['buy_num'] = 1;
                }
            }
        }
        $img = "";
        if ($c_id) {
            $img = Db::name('jifen_conf')->where(['conf_id' => $c_id])->value('conf_img');
        }
        return json(['status' => 200, 'msg' => $data, 'data' => $img]);
    }

    // 本地服务更多数据
    public function nativeMore()
    {
        extract(input());
        $where['shop_attestation'] = 2;
        $where['shop_status'] = 1;
        $where['shop_qu_id'] = $qu;
        $where['shop_native'] = 1;
        // 本地服务
        $p_native = Db::name('shop')
            ->where($where)
            ->field('shop_id,shop_range,shop_name,shop_img,shop_browse,shop_banner,shop_link,shop_introduce,shop_time,shop_qu_id,shop_lon,shop_lat,shop_address,shop_contact,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((' . $lat . '* PI() / 180 - shop_lat * PI() / 180) / 2),2) + COS(' . $lat . ' * PI() / 180) * COS(shop_lat * PI() / 180) * POW(SIN((' . $lon . ' * PI() / 180 - shop_lon * PI() / 180) / 2),2))),2) AS distance')
            ->order('shop_time')
            ->page($page, 10)
            ->select();
//        if (empty($p_native)) {
//        	unset($where['shop_qu_id']);
//        	$p_native   = Db::name('shop')
//                    ->where($where)
//                    ->field('shop_id,shop_range,shop_name,shop_img,shop_browse,shop_banner,shop_link,shop_introduce,shop_time,shop_qu_id,shop_lon,shop_lat,shop_address,shop_contact,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - shop_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(shop_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - shop_lon * PI() / 180) / 2),2))),2) AS distance')
//                    ->order('shop_time')
//                    ->page($page,10)
//                    ->select();
//        }
        if (!empty($p_native)) {
            foreach ($p_native as $key => $vo) {
                $product_ids = DB::name('product')->where('p_shop_id', $vo['shop_id'])->column('p_id');
                $shop_product = DB::name('product')
                    ->where('p_shop_id', $vo['shop_id'])
                    ->where('p_type', 1)
                    ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give')
                    ->limit(15)
                    ->order('p_add_time desc')
                    ->select();
                if (!empty($product_ids)) {
                    $star = DB::name('appraise')->where(['app_p_id' => ['in', $product_ids]])->avg('app_type');
                    if (!empty($star)) {
                        $star = ceil($star);
                        // 店铺星级，所有商品评价平均值
                        $p_native[$key]['p_star'] = $star;
                    } else {
                        // 没有商品给5星
                        $p_native[$key]['p_star'] = 5;
                    }
                } else {
                    // 没有商品给5星
                    $p_native[$key]['p_star'] = 5;
                }
                // 店铺商品
                $p_native[$key]['shop_product'] = $shop_product;
            }
        }
        // 按照星级排序
        if (!empty($sort) && $sort == 2) {
            $p_star = array_column($p_native, 'p_star');
            array_multisort($p_star, SORT_DESC, $p_native);
        }
        $img = Db::name('jifen_conf')->where(['conf_id' => 35])->value('conf_img');
        return json(['status' => 200, 'msg' => $p_native, 'data' => $img]);
    }

    // 同城购物搜索商品
    public function cashSearch()
    {
        extract(input());
        $data = Db::name('product')
            ->where(['p_type' => 1, 'p_status' => 4, 'p_name' => ['like', '%' . $key . '%']])
            ->page($page, 10)
            ->order('p_attestation_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $data]);
    }

    // 搜索店铺
    public function shopSearch()
    {
        extract(input());
        $data = DB::name('shop')
            ->where(['shop_attestation' => 2, 'shop_name' => ['like', '%' . $key . '%']])
            ->field('*,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((' . $lat . '* PI() / 180 - shop_lat * PI() / 180) / 2),2) + COS(' . $lat . ' * PI() / 180) * COS(shop_lat * PI() / 180) * POW(SIN((' . $lon . ' * PI() / 180 - shop_lon * PI() / 180) / 2),2))),2) AS distance')
            ->page($page, 10)
            ->order('shop_browse desc')
            ->select();
        if (!empty($data)) {
            foreach ($data as $key => $vo) {
                $product_ids = DB::name('product')->where('p_shop_id', $vo['shop_id'])->column('p_id');
                if (!empty($product_ids)) {
                    $star = DB::name('appraise')->where(['app_p_id' => ['in', $product_ids]])->avg('app_type');
                    if (!empty($star)) {
                        $star = ceil($star);
                        // 店铺星级，所有商品评价平均值
                        $data[$key]['p_star'] = $star;
                    } else {
                        // 没有商品给5星
                        $data[$key]['p_star'] = 5;
                    }
                } else {
                    // 没有商品给5星
                    $data[$key]['p_star'] = 5;
                }
            }
        }
        return json(['status' => 200, 'msg' => $data]);
    }

    // 搜索页展示
    public function searchShow()
    {
        extract(input());
        $data = [];
        switch ($type) {
            // 积分商品
            case 1:
                $where['p_type'] = ['in', '2,3'];
                $where['p_you_tj'] = 2;
                $where['p_status'] = 4;
                $where1['p_type'] = ['in', '2,3'];
                $where1['p_status'] = 4;
                $where1['p_search'] = 2;
                break;
            // 现金商品
            case 2:
                $where['p_type'] = 1;
                $where['p_status'] = 4;
                $where['p_you_tj'] = 2;
                $where1['p_type'] = 1;
                $where1['p_status'] = 4;
                $where1['p_search'] = 2;
                break;
        }
        // 为你推荐
        $p_you_tj = Db::name('product')
            ->where($where)
            ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give')
            ->page($page, 10)
            ->order('p_sort desc')
            ->select();
        // 热门搜索
        $p_hot_search = DB::name('product')
            ->where($where1)
            ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give')
            ->order('p_sort desc')
            ->limit(4)
            ->select();
        $data['p_you_tj'] = $p_you_tj;
        $data['p_hot_search'] = $p_hot_search;
        return json(['status' => 200, 'msg' => $data]);
    }

    // 购物车页展示(无商品)
    public function carShow()
    {
        extract(input());
        $data = [];
        // 为你推荐
        $p_you_tj = Db::name('product')->alias('p')
            ->join('shop sh', 'p.p_shop_id = sh.shop_id', 'left')
            ->where(['p_type' => 1, 'p_status' => 4, 'p_you_tj' => 2])
            ->field('p_id,p_shop_id,p_type,p_banner,p_name,p_old_price,p_now_price,p_jifen_price,p_stock_num,p_sell_yet,p_model,p_deliver_cate,p_give,p_postage,shop_name')
            ->page($page, 10)
            ->order('p_sort desc')
            ->select();
        if (!empty($p_you_tj)) {
            foreach ($p_you_tj as $key => $vo) {
                if ($vo['p_model'] == 2) {
                    $p_you_tj[$key]['p_model'] = DB::name('product_model')
                        ->where(['m_product_id' => $vo['p_id']])
                        ->select();
                } else {
                    $p_you_tj[$key]['p_model'] = '';
                }
                $p_you_tj[$key]['buy_num'] = 1;
            }
        }
        $data['p_you_tj'] = $p_you_tj;
        return json(['status' => 200, 'msg' => $data]);
    }

    // 店铺消费满多少送积分
    public function fullReduction()
    {
        extract(input());
        $record = DB::name('record_rule')
            ->where(['rule_shop_id' => $shop_id])
            ->order('rule_cash asc')
            ->select();
        if (!empty($record)) {
            $conf_rate = Db::name('jifen_conf')->where('conf_id', 1)->value('conf_rate');
            $shop_ratio = DB::name('shop')->where('shop_id', $shop_id)->value('shop_ratio');
            if (!empty($shop_ratio)) {
                foreach ($record as $k => $v) {
                    $ratio = (10 - $shop_ratio) / 10;
                    $record[$k]['rule_jifen'] = floor(($v['rule_cash'] * $ratio) / $conf_rate);
                }
            }
            return json(['status' => 200, 'msg' => $record]);
        } else {
            return json(['status' => 200, 'msg' => []]);
        }
    }
    public function getShopIdByS()
    {
        $shop_id = '';
        $urlsecretkey = input('urlsecretkey');
        $data = Db::name('shop_ercode')
            ->where('ss_urlparam', $urlsecretkey)
            ->find();
        if($data && $data['ss_shop_id']) $shop_id = $data['ss_shop_id'];
        if($shop_id) {
            $encrypt = $this->encrypt($shop_id,'ENCODE');
            return json(['status' => 200, 'msg' => $encrypt]);
        }else{
            return json(['status' => 100, 'msg' => '此码有误']);
        }
    }
    public function zhuxiao()
    {
        $user_id = input('user_id');
        $user = Db::name('u_user')->where('user_id', $user_id)->field('user_integral,user_balance')->find();
        if($user['user_balance'] > 0) return json(['status' => 100, 'msg' => '您的账号有未消费的余额']);
        if($user['user_integral'] > 0) return json(['status' => 100, 'msg' => '您的账号有未消费的积分']);
        $shop = Db::name('shop')->where('shop_user_id', $user_id)->field('shop_balance,shop_pledge_money,shop_integral')->find();
        if($shop){
            if($shop['shop_balance'] > 0) return json(['status' => 100, 'msg' => '您的商家账号有剩余余额']);
            if($shop['shop_pledge_money'] > 0) return json(['status' => 100, 'msg' => '您的商家账号有剩余押金']);
            if($shop['shop_integral'] > 0) return json(['status' => 100, 'msg' => '您的商家账号有剩余积分']);
        }
        Db::name('u_user')
            ->where('user_id', $user_id)
            ->setField('user_status', 2);
        return json(['status' => 200, 'msg' => '账号已注销！']);
    }
    //----------------------------------------------------------------------------------------------------------------------------------
    public function userHeHuoRen()
    {
        extract(input());
        $user = Db::name('u_user')->where(['user_id' => $user_id])->value('user_level');
        return json(['status' => 200, 'msg' => $user]);
    }
    /**
     * 新建
     */
    public function addLive()
    {
        extract(input());
//        $link = 'https://jintianjifen.oss-cn-shanghai.aliyuncs.com/bed99550658535a20b2669fadfa3f01c.jpg';
//        $link2 = 'https://jintianjifen.oss-cn-shanghai.aliyuncs.com/1581999532227';
//        $user_id=1;$content='hhhhh';$start_time = time() + 3600;$end_time = time() + 7200;
//        $anchorName='张三';$anchorWechat='mww19900115';
//        if (isset($mini)) {
//            $result = $this->msgSecCheck($content);
//            if($result['code'] == 0){
//                return json(['status' => 100, 'msg' => $result['msg']]);
//            }
//        }
        $user = Db::name('u_user')->where(['user_id' => $user_id])->find();
        if ($user['user_level'] <= 1) {
            return json(['status' => 100, 'msg' => '只有合伙人才可以开直播']);
        }
        if ($user['user_image'] == '' || preg_match("/^1[3456789]\d{9}$/", $user['user_username'])) {
            return json(['status' => 100, 'msg' => '发布动态需要先完善个人资料']);
        }
        if(!$user['user_invite_code']) return json(['status' => 100, 'msg' => '邀请码错误，请联系管理员！']);
        $six = Db::name('posts')->where(['post_user_id' => $user_id])->whereTime('post_add_time', '-30 minutes')->count();
//        if ($six > 0 && $user_id != 12) {
//            return json(['status' => 100, 'msg' => '半小时后再发帖子']);
//        }
        $imgBig = $this->imgBigFalse($link,1);
        if(!$imgBig) return json(['status' => 100, 'msg' => '背景墙图片不能超过2M']);
        $imgBig = $this->imgBigFalse($link2,2);
        if(!$imgBig) return json(['status' => 100, 'msg' => '分享卡片封面图不能超过1M']);
        $imgBig = $this->imgBigFalse($link3,3);
        $img_info = file_get_contents($link3 . '?x-oss-process=image/info');
        $img_info = json_decode($img_info,true);
        if(!$imgBig) return json(['status' => 100, 'msg' => $img_info['FileSize']['value'] . '直播频道封面图不能超过100K~'.$link3]);
        $post_link_mediaID = $this->uploadLiveImg($link);
        $post_link_mediaID2 = $this->uploadLiveImg($link2);
        $post_link_mediaID3 = $this->uploadLiveImg($link3);
        if(!$post_link_mediaID || !$post_link_mediaID2 || !$post_link_mediaID3) return json(['status' => 100, 'msg' => '微信上传失败，请稍后再试~']);
        //--------------申请-------------------
//        $post_link_mediaID = 'DmP8AnOMImtVu-g5uQNbDJKXsl8XNhnqBiFS0MUPtMh82l_-Y5imGVt-o7C_hJfv';
//        $post_link_mediaID2 = 'DmP8AnOMImtVu-g5uQNbDEq8W0ptPhZQPGMsa7nFTHHrNDc4z2tQmUQyDKTjW0id';
        if(mb_strlen($content) < 3 || mb_strlen($content) > 17) return json(['status' => 100, 'msg' => '直播间名字最短3个汉字，最长17个汉字']);
        if(mb_strlen($anchorName) < 2 || mb_strlen($anchorName) > 15) return json(['status' => 100, 'msg' => '主播昵称最短2个汉字，最长15个汉字']);
        $dataWx = [
            'name' => $content,
            'coverImg' => $post_link_mediaID,
            'startTime' => (int)strtotime($start_time),
            'endTime' => (int)strtotime($end_time),
            'anchorName' => $anchorName,
            'anchorWechat' => $anchorWechat,
            'shareImg' => $post_link_mediaID,
            'feedsImg' => $post_link_mediaID2,
            'type' => 0,
            'closeLike' => 0,
            'closeGoods' => 0,
            'closeComment' => 0,
        ];
        if($dataWx['startTime'] >= time() + 86400*180) return json(['status' => 100, 'msg' => '开播时间需要在当前时间的10分钟后 并且开始时间不能在6个月后']);
        $timecha = $dataWx['endTime'] - $dataWx['startTime'];
        if($timecha <= 1800 || $timecha >= 86400) return json(['status' => 100, 'msg' => '开播时间和结束时间间隔不得短于30分钟，不得超过24小时']);
        $TOKEN=$this->getAccessTokenLive();
        $URL ='https://api.weixin.qq.com/wxaapi/broadcast/room/create?access_token='.$TOKEN;
        $obj = https_request($URL,http_build_query($dataWx),'POST');
        $result = json_decode($obj,true);
        $qrcode_url = '';
        if(isset($result['roomId']) && $result['roomId']){
            $room_id = $result['roomId'];
            if(isset($result['qrcode_url']) && $result['qrcode_url']) $qrcode_url = $result['qrcode_url'];
            //----导入商品-------
            if($user['user_shop_id']){
                $goodids = Db::name('product')
                    ->where('p_shop_id',$user['user_shop_id'])
                    ->where('p_status',4)
                    ->where('p_live',3)
                    ->where('p_live_goodid','>',0)
                    ->column('p_live_goodid');
                if($goodids){
                    $goodData = [
                        'ids' => $goodids,
                        'roomId' => $room_id
                    ];
                    $URL ='https://api.weixin.qq.com/wxaapi/broadcast/room/addgoods?access_token='.$TOKEN;
                    $obj = https_request($URL,http_build_query($goodData),'POST');
                    $result = json_decode($obj,true);
                    if(isset($result['errmsg']) && $result['errmsg']) return json(['status' => 100, 'msg' => $result['errmsg']]);
                }
            }
            //----导入商品-end------
        }else{
            if(isset($result['qrcode_url']) && $result['qrcode_url']) {
                $qrcode_text = "首次开播，请此微信号主播长按识别此图片前往“小程序直播”实名认证！";
                return json(['status' => 666, 'msg' => $result['qrcode_url'], 'qrcode_text' => $qrcode_text]);
            }
            return json(['status' => 100, 'msg' => $result['errmsg']]);
            return json(['status' => 100, 'msg' => '直播间创建失败，请稍后重试~']);
        }
        //--------------申请-end------------------
        $param = [
            'post_type'       => 1,
            'post_content'    => $content,
            'post_link'       => $link,
            'post_link2'       => $link2,
            'post_link3'       => $link3,
            'post_link_mediaID' => $post_link_mediaID,
            'post_link_mediaID2' => $post_link_mediaID2,
            'post_link_mediaID3' => $post_link_mediaID3,
            'post_user_id'    => $user_id,
            'post_share_post' => $share_id,
            'post_add_time'   => date('Y-m-d H:i:s'),
            'post_lon'        => $lon,
            'post_lat'        => $lat,
            'post_live'        => 2,
            'post_room_id'        => $room_id,
            'post_start_time'        => $start_time,
            'post_end_time'        => $end_time,
            'post_user_code'        => $user['user_invite_code'],
        ];
        $res = Db::name('posts')->insertGetId($param);
        if ($res) {
            $qrcode_text = "直播创建成功！但主播微信号尚未在‘小程序直播’小程序实名认证，请此微信号主播长按识别此图片前往认证或直接搜索‘小程序直播’小程序前往认证";
            return json(['status' => 200, 'msg' => '发布成功', 'id' => $res, 'qrcode_url' => $qrcode_url, 'qrcode_text' => $qrcode_text]);
        } else {
            return json(['status' => 100, 'msg' => '发布失败', 'id' => '']);
        }
    }
    public function uploadLiveImg($imgUrl,$type=1)
    {
        $TOKEN=$this->getAccessTokenLive();
        if($type == 1) $imgUrl = $this->getImageLocation($imgUrl);
        $URL ='https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$TOKEN.'&type=image';
        $data = [
            'media' => new \CURLFile($imgUrl)
        ];
        $obj = https_request($URL,$data,'POST');
        $result = json_decode($obj,true);
        if(isset($result['media_id']) && $result['media_id']){
            return $result['media_id'];
        }
        return '';
    }
    public function getAccessTokenLive(){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.config('mini.appId').'&secret='.config('mini.appSecret');
        $obj = https_request($url);
        $arr = json_decode($obj, true);
        if(isset($arr['errcode'])){
            return '';
        }
        return $arr['access_token'];
    }
    public function getImageLocation($imgUrl){

        import('aliyun.autoload', EXTEND_PATH);
        $accessKeyId = "LTAI9ltsS4tONPhv";
        $accessKeySecret = "PdQsbzveOa2JVVya7WNcfNOZoutwjM";
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "oss-cn-shanghai.aliyuncs.com";
        // 填写Bucket名称。
        $bucket= "jintianjifen";
        // 填写不包含Bucket名称在内的Object完整路径，例如testfolder/exampleobject.txt。
        $imgArr = explode('/',$imgUrl);
        $object = end($imgArr);
        // 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
        //// 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
        $loadName = time() . rand(10000,99999) . '.jpg';
        $new_file = ROOT_PATH . 'public' . DS . 'live/' . date ('Ymd') . "/";
        if ( !file_exists ($new_file) ) {
            mkdir ($new_file , 0700,true);
        }
        $localfile = $new_file . $loadName;
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $localfile
        );
        // 使用try catch捕获异常。如果捕获到异常，则说明下载失败；如果没有捕获到异常，则说明下载成功。
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $ossClient->getObject($bucket, $object, $options);
        return $localfile;
    }
    public function imgBigFalse($imgUrl,$type){
        $flag = true;
        if($imgUrl){
            $sizeMax = 2000000;
            if($type == 2) $sizeMax = 1000000;
            if($type == 3) $sizeMax = 100000;
            $img_info = file_get_contents($imgUrl . '?x-oss-process=image/info');
            $img_info = json_decode($img_info,true);
            if($img_info['FileSize']['value'] > $sizeMax) $flag = false;
        }
        return $flag;
    }
//    public function aaa()
//    {
//        $TOKEN=$this->getAccessTokenLive();
//        $goodData = [
//            'ids' => [1],
//            'roomId' => 18
//        ];
//        $URL ='https://api.weixin.qq.com/wxaapi/broadcast/room/addgoods?access_token='.$TOKEN;
//        $obj = https_request($URL,http_build_query($goodData),'POST');
//        $result = json_decode($obj,true);
//        dump($result);die;
//        if(isset($result['errmsg']) && $result['errmsg']) return json();
//    }
}